我想在用户离开页面之前做一个确认。如果他说ok,那么它将重定向到新的页面或取消离开。我试着用onunload来做

<script type="text/javascript">
function con() {
    var answer = confirm("do you want to check our other products")
    if (answer){

        alert("bye");
    }
    else{
        window.location = "http://www.example.com";
    }
}
</script>
</head>

<body onunload="con();">
<h1 style="text-align:center">main page</h1>
</body>
</html>

但它确认后,页面已经关闭?如何正确地做呢?

如果有人展示如何用jQuery来做,那就更好了。


当前回答

只是更有用一点,启用和禁用

$(window).on('beforeunload.myPluginName', false); // or use function() instead of false
$(window).off('beforeunload.myPluginName');

其他回答

只是更有用一点,启用和禁用

$(window).on('beforeunload.myPluginName', false); // or use function() instead of false
$(window).off('beforeunload.myPluginName');

此代码还用于检测窗体状态是否发生变化。

$('#form').data('serialize',$('#form').serialize()); // On load save form current state

$(window).bind('beforeunload', function(e){
    if($('#form').serialize()!=$('#form').data('serialize'))return true;
    else e=null; // i.e; if form state change show warning box, else don't show it.
});

你可以谷歌JQuery表单序列化函数,这将收集所有表单输入并保存在数组中。我想这个解释就足够了:)

这将在离开当前页面时发出警报

<script type='text/javascript'>
function goodbye(e) {
    if(!e) e = window.event;
    //e.cancelBubble is supported by IE - this will kill the bubbling process.
    e.cancelBubble = true;
    e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog

    //e.stopPropagation works in Firefox.
    if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
}
window.onbeforeunload=goodbye; 

</script>

通常情况下,当用户在表单中进行了更改,但这些更改没有保存时,您希望显示此消息。

采用这种方法只在用户更改某些内容时才显示消息

var form = $('#your-form'),
  original = form.serialize()

form.submit(function(){
  window.onbeforeunload = null
})

window.onbeforeunload = function(){
  if (form.serialize() != original)
    return 'Are you sure you want to leave?'
}

这就是我所做的显示确认消息,只是当我有未保存的数据

window.onbeforeunload = function() {
  if (isDirty) {
    return 'There is unsaved data.';
  }
  return undefined;
}

返回undefined将禁用确认

注意:返回null将不能在IE中工作

您还可以使用undefined禁用确认

window.onbeforeunload = undefined;