我尝试了以下代码,以便在关闭浏览器窗口时收到警告:
window.onbeforeunload = confirmExit;
function confirmExit() {
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
它是有效的,但如果页面包含一个超链接,则单击该超链接会引发相同的警报。我只需要在关闭浏览器窗口时显示警告,而不是单击超链接。
发布于 2008-12-02 11:19:29
保持代码原样,并使用jQuery处理链接:
$(function () {
$("a").click(function {
window.onbeforeunload = null;
});
});
发布于 2008-12-02 11:20:11
另一个实现如下,你可以在这个网页上找到它:http://ujap.de/index.php/view/JavascriptCloseHook
<html>
<head>
<script type="text/javascript">
var hook = true;
window.onbeforeunload = function() {
if (hook) {
return "Did you save your stuff?"
}
}
function unhook() {
hook=false;
}
</script>
</head>
<body>
<!-- this will ask for confirmation: -->
<a href="http://google.com">external link</a>
<!-- this will go without asking: -->
<a href="anotherPage.html" onClick="unhook()">internal link, un-hooked</a>
</body>
</html>
它所做的就是使用一个变量作为标志。
https://stackoverflow.com/questions/333665
复制相似问题