离开页面之前的JavaScript

离开页面之前的JavaScript

本文介绍了离开页面之前的JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用户离开页面之前做出确认。如果他说好,那么它将重定向到新页面或取消离开。我尝试使用onunload

I want to make a confirmation before user leaving the page. If he says ok then it would redirect to new page or cancel to leave. I tried to make it with 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>

但在页面已经关闭后确认?如何正确地做到这一点?

But it confirm after page already closed? How to do it properly?

如果有人用jQuery演示如何做到这一点会更好吗?

It would be even better if someone shows how to do it with jQuery?

推荐答案

onunload (或 onbeforeunload )无法将用户重定向到其他页面。这是出于安全原因。

onunload (or onbeforeunload) cannot redirect the user to another page. This is for security reasons.

如果要在用户离开页面之前显示提示,请使用 onbeforeunload

If you want to show a prompt before the user leaves the page, use onbeforeunload:

window.onbeforeunload = function(){
  return 'Are you sure you want to leave?';
};

或者使用jQuery:

Or with jQuery:

$(window).bind('beforeunload', function(){
  return 'Are you sure you want to leave?';
});

这只会询问用户是否要离开页面,如果用户不想重定向,他们选择留在页面上。如果他们选择离开,浏览器将转到他们告诉它去的地方。

This will just ask the user if they want to leave the page or not, you cannot redirect them if they select to stay on the page. If they select to leave, the browser will go where they told it to go.

你可以使用 onunload 来在页面卸载之前执行操作,但您无法从那里重定向(Chrome 14+阻止 onunload 内的警报):

You can use onunload to do stuff before the page is unloaded, but you cannot redirect from there (Chrome 14+ blocks alerts inside onunload):

window.onunload = function() {
    alert('Bye.');
}

或者使用jQuery:

Or with jQuery:

$(window).unload(function(){
  alert('Bye.');
});

这篇关于离开页面之前的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 11:57