页面中的条件onbeforeunload事件

zka*_*oca 9 javascript jquery

window.onbeforeunload = function(evt) {
    var message = 'Are you sure you want to leave the page. All data will be lost!';

    if (typeof evt === 'undefined') {
        evt = window.event;
    }
    if (evt && !($("#a_exit").click)) {
        evt.returnValue = message;
    }
    return message;
};
Run Code Online (Sandbox Code Playgroud)

我希望用户只在页面上点击链接(有id ="a_exit").在其他情况下,例如刷新页面,单击另一个链接,将提示用户他/她是否要离开页面.我试过使用上面的代码.当我点击退出链接时,它仍然会询问我是否要离开.

Nik*_*ojo 5

$(window).bind('beforeunload',function() {
    return "'Are you sure you want to leave the page. All data will be lost!";
});

$('#a_exit').live('click',function() {
    $(window).unbind('beforeunload');
});
Run Code Online (Sandbox Code Playgroud)

以上对我有用


Sim*_*mon 1

window.onbeforeunload您只需在点击处理程序中删除即可。

  • 我猜它不会工作,但在最后的 chrome、IE 和 FF 下测试,它可以工作 http://jsfiddle.net/Suf99/ (2认同)