简体   繁体   English

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

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

How can I call another Java Script function if I confirm Yes on below window.onbeforeunload event. 如果我在window.onbeforeunload事件下面确认是,如何调用另一个Java脚本函数。

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

How can I call another Java Script function if I confirm Yes on below window.onbeforeunload event. 如果我在window.onbeforeunload事件下面确认是,如何调用另一个Java脚本函数。

If by "yes" you mean "Yes, leave" then you might be able to use the unload event on window . 如果用“是”表示“是,请离开”,那么您也许可以在window上使用unload事件。 Note that you can't do much of anything at that point. 请注意,此时您无法做任何事情。

If by "yes" you mean "Yes, stay on the page" then you can do that just by setting a timed callback with setTimeout . 如果用“是”表示“是,留在页面上”,则可以通过设置setTimeout的定时回调来实现。

Here's a complete example which records to local storage whether you left or stayed (tested on Firefox, Chrome, and IE11): 这是一个完整的示例,该记录将您离开还是停留在本地存储中(在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>

I believe you need the function 我相信你需要的功能

confirm(message)

Depending on what you click ("Ok" or "Cancel"), it returns a boolean value. 根据您单击的内容(“确定”或“取消”),它将返回一个布尔值。 After testing for this return value, you can take an action you want. 测试此返回值后,您可以执行所需的操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM