我想在用户点击关闭按钮时,像Google文档一样询问用户是否真的要离开页面。如何使用jQuery实现此功能?
我想在用户点击关闭按钮时,像Google文档一样询问用户是否真的要离开页面。如何使用jQuery实现此功能?
你将窗口的 onbeforeunload
属性设置为一个函数。
或者另一个例子:
<script language="JavaScript">
var needToConfirm = true;
window.onbeforeunload = confirmExit;
function confirmExit()
{
if (needToConfirm)
//return message to display in dialog box;
}
</script>
...
<input type="Submit" value="Save" onclick="needToConfirm = false;" />
要为表单设置needToConfirm
,您可以执行以下操作:
$(document).ready(function() {
$(':input', document.myForm).bind("change", function() { needToConfirm = true; }); // Prevent accidental navigation away
});
$(window).unload(function() {
if(event.clientY < 0) {
//do whatever you want when closing the window..
}
});
$(window).bind('beforeunload', function() { ... });
- Alexis Wilke