如何使window.onbeforeunload jquery仅在关闭选项卡时工作?
我正在使用下面的代码,它将显示“确定要离开?”对话框,即使在重定向到另一个页面时也是如此。我只需要在关闭选项卡时弹出此对话框。 那么,该代码中需要进行哪些修改如何使window.onbeforeunload jquery仅在关闭选项卡时工作?,jquery,Jquery,我正在使用下面的代码,它将显示“确定要离开?”对话框,即使在重定向到另一个页面时也是如此。我只需要在关闭选项卡时弹出此对话框。 那么,该代码中需要进行哪些修改 <script> window.onbeforeunload = function (event) { var message = 'Sure you want to leave?'; if (typeof event == 'undefined') {
<script>
window.onbeforeunload = function (event) {
var message = 'Sure you want to leave?';
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
}
$(function () {
$("a").not('#lnkLogOut').click(function () {
window.onbeforeunload = null;
});
$(".btn").click(function () {
window.onbeforeunload = null;
});
});
</script>
window.onbeforeunload=函数(事件){
var message='确定要离开吗?';
如果(事件类型==“未定义”){
event=window.event;
}
如果(事件){
event.returnValue=消息;
}
返回消息;
}
$(函数(){
$(“a”)。不是(“#lnkLogOut”)。单击(函数(){
window.onbeforeunload=null;
});
$(“.btn”)。单击(函数(){
window.onbeforeunload=null;
});
});
我认为我们没有特定于选项卡的事件。
这里您所能做的就是定义一个全局变量,并在重定向到其他页面的点击链接上设置它。
通过检查变量是否已设置,您可以防止onbeforeunload事件相应地触发。我认为您需要显示“警报”窗口才能使其工作:
window.onbeforeunload = function (event) {
var message = 'Sure you want to leave?';
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
alert(message);
return message;
}
$(function () {
$("a").not('#lnkLogOut').click(function () {
window.onbeforeunload = null;
});
$(".btn").click(function () {
window.onbeforeunload = null;
});
});
你想达到什么目标
beforeunload
确实可以防止在用户可能丢失更改(例如未保存的工作)的情况下进行页面导航
您不应该试图区分关闭选项卡的用户和通过其他方式(例如超链接)离开当前页面的用户