【发布时间】:2017-01-24 02:17:19
【问题描述】:
我正在尝试做一些类似于您离开的某些网站的操作,它会显示一个弹出窗口,上面写着“您确定要离开此页面吗”,并有两个选项说“取消”和“确定”。
我将如何做到这一点并做到这一点,当您单击“取消”时,它只会取消该框,而当他们单击“确定”时,它将执行“leaveChat();”运行并离开网站?
我尝试过使用 onbeforeunload ,但我不确定功能部分。
感谢您的帮助!
【问题讨论】:
我正在尝试做一些类似于您离开的某些网站的操作,它会显示一个弹出窗口,上面写着“您确定要离开此页面吗”,并有两个选项说“取消”和“确定”。
我将如何做到这一点并做到这一点,当您单击“取消”时,它只会取消该框,而当他们单击“确定”时,它将执行“leaveChat();”运行并离开网站?
我尝试过使用 onbeforeunload ,但我不确定功能部分。
感谢您的帮助!
【问题讨论】:
没有办法做到这一点。
您可以尝试在onunload 中发送 AJAX 请求,但我认为这不会可靠。
【讨论】:
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!");
}
}
【讨论】: