我有一个系统,我想在其中检查用户是否确定他们想要在设置脏标志后离开页面。
我正在使用以下代码 - 在 FireFox 中,我可以通过 FireBug 查看页面源代码,并且标签中正确插入了 onbeforeunload 属性。
在 Chrome 和 FireFox 中,这不会发生,我可以在没有任何警告的情况下离开页面。更新 body 标记的 jQuery 行肯定正在执行,它只是没有执行它。
if ($("body").attr('onbeforeunload') == null) {
if (window.event) {
// IE and Chrome use this
$("body").attr('onbeforeunload', 'CatchLeavePage(event)');
}
else {
// Firefox uses this
$("body").attr('onbeforeunload', 'return false;CatchLeavePage(event)');
}
}
有什么想法可以从这里开始吗?
最佳答案
您不能通过返回 false 来中止页面卸载。您必须返回将在消息框中显示给用户的字符串,并且他决定是要离开还是留在页面上(通过选择“确定”或“取消”按钮),因此您需要编写代码这个:
window.onbeforeunload = function() {
return "Are you sure you want to leave this page bla bla bla?"; // you can make this dynamic, ofcourse...
};
关于javascript - 使用 jQuery 在 Chrome 和 IE 中的 body 元素上设置 onbeforeunload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1802930/