如果我在window.onbeforeunload事件上确认是,我该如何调用另一个Java Script函数

时间:2015-03-10 10:42:04

标签: javascript asp.net

如果我在下面的window.onbeforeunload事件中确认是,我怎么能调用另一个Java Script函数。

function closeIt() {
return "You have attempted to leave this page. Are you sure you want to exit";
}
window.onbeforeunload = closeIt;

2 个答案:

答案 0 :(得分:0)

  

如果我在下面的window.onbeforeunload事件中确认是,我怎么能调用另一个Java Script函数。

如果是"是"你的意思是"是的,离开"那么您可以在unload上使用window事件。请注意,此时您无法做任何事情。

如果是"是"你是说"是的,留在页面"然后你可以通过设置setTimeout的定时回调来实现。

这是一个完整的示例,可以记录到本地存储,无论您是离开还是留下(在Firefox,Chrome和IE11上测试):

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Closing</title>
<style>
html {
  box-sizing: border-box;
}
*, *:before, *:after {
  box-sizing: inherit;
}
body {
  font-family: sans-serif;
}
</style>
</head>
<body>
<script>
(function() {
    display("foo = " + (localStorage.getItem("foo") || "<em>not set</em>"));

    window.onbeforeunload = function() {
        setTimeout(function() {
            localStorage.setItem("foo", "stayed at " + new Date());
            display("Stayed");
        }, 10);
        return "Really leave?";

    };
    if (window.addEventListener) {
        window.addEventListener("unload", left, false);
    } else if (window.attachEvent) {
        window.attachEvent("onunload", left);
    } else {
        window.onunload = left;
    }

    function left() {
        localStorage.setItem("foo", "left at " + new Date());
    }

    function display(msg) {
        var p = document.createElement('p');
        p.innerHTML = String(msg);
        document.body.appendChild(p);
    }
})();
</script>
</body>
</html>

答案 1 :(得分:0)

我相信你需要这个功能

confirm(message)

根据您单击的内容(“确定”或“取消”),它返回一个布尔值。在测试此返回值后,您可以执行所需的操作。

if(confirm("Are you sure?")) {
    alert("Yes, you are!")};
} else {
    alert("Why not?")
}