Javascript 如何收集onbeforeunload的返回值
如果用户试图关闭窗口而不保存表单,我将显示一条警告消息Javascript 如何收集onbeforeunload的返回值,javascript,dom-events,onbeforeunload,Javascript,Dom Events,Onbeforeunload,如果用户试图关闭窗口而不保存表单,我将显示一条警告消息 window.onbeforeunload = askConfirm; function askConfirm() { // needToConfirm is set to true if any changes are there in the form if (needToConfirm) { return "Your unsaved data w
window.onbeforeunload = askConfirm;
function askConfirm()
{
// needToConfirm is set to true if any changes are there in the form
if (needToConfirm)
{
return "Your unsaved data will be lost.";
}
}
function call_this_if_user_clicks_on_cancel()
{
// Bla bla bla
// After this user should remain on the same page.
}
现在我想在用户单击ok
时调用另一个函数。其余的功能应该保持不变。
那么,如何收集onbeforeuload
返回值并调用另一个函数呢
解决方案:
needToConfirm = false;
window.onbeforeunload = askConfirm;
window.onunload = unloadPage;
isDelete = true;
function unloadPage()
{
if(isDelete)
{
call_this_if_user_clicks_on_cancel()
}
}
function askConfirm()
{
alert("onbeforeunload");
if (needToConfirm)
{
// Message to be displayed in Warning.
return "Your data will be lost.";
}
else
{
isDelete = false;
}
}
我不确定;但是我认为你不能调用另一个函数,作为浏览器的预防措施,这样它就不会因为离开页面而被困住 我认为只有浏览器知道它是否返回true/false来确定页面是否已卸载(或未卸载) 以前的unbeforeunload是非标准的(来自IE4,但受其他浏览器支持) 这是Mozilla文档 和Microsoft文档: 然而,HTML5提案中的Unloadevent看起来与之前的想法一样。 本文档详细介绍了卸载文档时发生的步骤(有趣的阅读):
作为解决办法: 您可以从“卸载事件”中收集所需的信息,如果在onbeforeunload之后未调用卸载事件,则可以假定用户选择留在您的页面上
您的意思是希望在卸载之前启用“secondary”
?我认为您可以调用该函数,而不是返回代码并传递字符串。如果我正确理解您的问题。@Shadow:如果用户单击“取消”,我想执行一些步骤,其余部分应该与default@Felix:是的,但附近有工作吗?@Asad:是的。如果你能提供一些细节就太好了。@Alex:谢谢你,伙计。这正是我想要的。现在这听起来不是不可能的。@Ajinkya:不用担心,很高兴能提供帮助,我很想看看你们相处得怎么样。如果这对你来说合适的话,请在这里留下评论。@Alex:这是可行的,但是每当我单击任何其他链接时,都会调用onunload
。@Ajinkya:是的,onbeforeunload和onunload都会被调用,只要导致文档卸载,即导航到其他地方。如果您只在某些链接上需要它,您可以在单击事件中附加事件(例如,在卸载之前附加它)。@Alex:我尝试了一些临时解决方案。我已使用解决方案更新了我的问题。