Cancel onbeforeunload event handler?

前端 未结 4 853
孤独总比滥情好
孤独总比滥情好 2021-01-07 18:41

I have an onbeforeunload event handler attached to the page which executes every time the page reloads / gets redirected.

window.onbeforeunload = function()          


        
4条回答
  •  醉梦人生
    2021-01-07 18:44

    jQuery ≥ 1.7

    With jQuery 1.7 onward the event API has been updated, .bind()/.unbind() are still available for backwards compatibility, but the preferred method is using the on()/off() functions. The below would now be,

    $('#myimage').click(function() { return false; }); // Adds another click event
    $('#myimage').off('click');
    $('#myimage').on('click.mynamespace', function() { /* Do stuff */ });
    $('#myimage').off('click.mynamespace');
    $( window ).on( "unload", handler )
    

    As the .unload() method is just a shorthand for .on( "unload", handler ), detaching is possible using .off( "unload" )

    $( window ).off( "unload", handler )
    

提交回复
热议问题