我正在尝试做一些类似于您离开的某些网站的事情,它会显示一个弹出窗口,上面写着“您确定要离开此页面”,并带有两个选项,即“取消”和“确定”。
我将如何做到这一点并做到这一点,当您单击“取消”时,它只会取消该框,而当他们单击“确定”时,它将执行“leaveChat();” 功能并离开网站?
我试过使用 onbeforeunload ,但我不确定功能部分。
谢谢您的帮助!
我正在尝试做一些类似于您离开的某些网站的事情,它会显示一个弹出窗口,上面写着“您确定要离开此页面”,并带有两个选项,即“取消”和“确定”。
我将如何做到这一点并做到这一点,当您单击“取消”时,它只会取消该框,而当他们单击“确定”时,它将执行“leaveChat();” 功能并离开网站?
我试过使用 onbeforeunload ,但我不确定功能部分。
谢谢您的帮助!
要在用户离开页面时弹出消息以确认离开,您只需执行以下操作:
<script>
window.onbeforeunload = function(e) {
return 'Are you sure you want to leave this page? You will lose any unsaved data.';
};
</script>
调用函数:
<script>
window.onbeforeunload = function(e) {
callSomeFunction();
return null;
};
</script>
这是我的html
<!DOCTYPE HMTL>
<meta charset="UTF-8">
<html>
<head>
<title>Home</title>
<script type="text/javascript" src="script.js"></script>
</head>
<body onload="myFunction()">
<h1 id="belong">
Welcome To My Home
</h1>
<p>
<a id="replaceME" onclick="myFunction2(event)" href="https://www.ccis.edu">I am a student at Columbia College of Missouri.</a>
</p>
</body>
这就是我在 javaScript 中做类似事情的方式
var myGlobalNameHolder ="";
function myFunction(){
var myString = prompt("Enter a name", "Name Goes Here");
myGlobalNameHolder = myString;
if (myString != null) {
document.getElementById("replaceME").innerHTML =
"Hello " + myString + ". Welcome to my site";
document.getElementById("belong").innerHTML =
"A place you belong";
}
}
// create a function to pass our event too
function myFunction2(event) {
// variable to make our event short and sweet
var x=window.onbeforeunload;
// logic to make the confirm and alert boxes
if (confirm("Are you sure you want to leave my page?") == true) {
x = alert("Thank you " + myGlobalNameHolder + " for visiting!");
}
}
没有办法做到这一点。
您可以尝试在 中发送 AJAX 请求onunload
,但我认为这不会可靠地工作。