我需要使用JavaScript或PHP在关闭浏览器窗口之前显示确认对话框。
确认框应该在我单击浏览器的关闭按钮时出现。否则不显示对话框。
请帮帮我。
你应该处理 onbeforeunload 事件...
function closeEditorWarning(){
return 'Are you sure?'
}
window.onbeforeunload = closeEditorWarning;
或者使用jQuery,window.attachEvent / window.addEventListener 来实现更好的效果
onunload
在我看来并不是很有用,因为你无法对你请求的 confirm
做任何事情(除了可能尝试使用 window.open
打开一个新窗口),所以在这种情况下,onbeforeunload
更加有用。
你最好使用 onbeforeunload
,它非常好用,但在 Opera 中不起作用(虽然这通常不是致命问题)。
就像 Ivy 说的那样,它会看起来像这样:
<script>
var userIsEditingSomething; // set this if something crazy happens
oldOnBeforeUnload = window.onbeforeunload;
window.onbeforeunload = function () {
// attempt to handle a previous onbeforeunload
if ('function' === typeof oldOnBeforeUnload) {
var message = oldOnBeforeUnload();
if ('undefined' !== typeof message) {
if (confirm('string' === typeof message ? message : 'Are you sure you want to leave this page?')) {
return; // allow user to exit without further annoying pop-ups
}
}
}
// handle our own
if (userIsEditingSomething) {
return 'Are you sure you want to exit?';
}
};
</script>
function doUnload()
{
// use confirm dialog box here
confirm("Window is closing...");
}
<body onunload="doUnload()">
undefined
。但是,如果你返回null
或false
,IE 将显示一条消息,询问你是否想要使用 null 或 false,这似乎有些奇怪。 - KajMagnus