离开页面前的 JavaScript [英] JavaScript before leaving the page

查看:13
本文介绍了离开页面前的 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆