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

How can I call another Java Script function if I confirm Yes on window.onbeforeunload event

本文关键字:调用 Java 函数 脚本 何调用 另一个 onbeforeunload window 事件 如果 确认      更新时间:2023-09-26

如果我在下面的window.onbeforeunload事件上确认是,我如何调用另一个Java脚本函数。

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

如果我在下面的 window.onbeforeunload 事件上确认是,我如何调用另一个 Java 脚本函数。

如果"是"的意思是"是,离开",那么您可以在window上使用unload事件。请注意,此时您不能做太多事情。

如果"是"的意思是"是,留在页面上",那么您只需使用 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>

我相信你需要这个函数

confirm(message)

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

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