How can I prevent [removed] from being triggered by [removed] href links in IE?

前端 未结 6 1710
清酒与你
清酒与你 2021-01-30 05:24

I\'m building a fail safe for my form that is going to warn users that if they leave the page their form data will be lost (similar to what gmail does).

window.         


        
6条回答
  •  天涯浪人
    2021-01-30 06:13

    (Like some of the other answers, this requires changing how the JavaScript is bound. If that doesn't work for you, disregard.)

    I found that in IE 7 through IE 10, simply using jQuery .click() with preventDefault works without showing the onbeforeunload message (IE 11 does not show the beforeunload message for any of my test cases). This is true whether the href is '#' or javascript:void(0). I expect the conclusion holds if attachEvent/addEventListener is used directly, but I didn't test that.

    There is a demo of the below at http://jsbin.com/tatufehe/1 . Both of the versions (in green) with preventDefault work (don't show the beforeunload dialog). The one without preventDefault does show it (as a comparison).


    $( document ).ready( function () {
      $( 'a' ).click( function ( evt ) {
        $( '#display' ).text( 'You clicked: ' + $( this ).text() );
    
        if ( $(this).hasClass( 'withPreventDefault' ) ) {
          evt.preventDefault();
        }
      } );
    })
    
    window.onbeforeunload = function () {
      return "Are you sure you want to leave?";   
    };
    

    Number sign link *with* preventDefault

    JavaScript href link *with* preventDefault

    JavaScript href link *without* preventDefault

提交回复
热议问题