如果未提交表单,则触发onb​​eforeunload [英] Trigger onbeforeunload if form is not submitted

查看:99
本文介绍了如果未提交表单,则触发onb​​eforeunload的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过PHP提交的表单,其中包含3个提交操作:

I've got a form which is being submitted via PHP with 3 submit actions:

  • 保存并继续
  • 保存并退出
  • 不保存即退出

如果用户不单击任何表单操作来建议他们离开页面,并且他们的更改可能不会保存,则我想触发"OnBeforeUnload"警报以显示.

I'd like to trigger an "OnBeforeUnload" alert to display if the user DOES NOT click on any of the form actions to advise them that they're leaving the page, and their changes may not be saved.

我尝试了以下代码,但是好像在点击事件之前触发了unbeforeunload.关于如何最好地实现这一目标的任何建议?

I've tried the following code but it seems as though the unbeforeunload is being triggered before my click event. Any suggestions on how best to achieve this?

$buttonpressed = false;
$j(".Actions input").click(function(){
    $buttonpressed = true;                                  
});

if(!$buttonpressed){
    window.onbeforeunload = function(){
        return "Your changes may not be saved.";
    }
}

推荐答案

您需要在处理程序内部中进行检查,如下所示:

You need to do the check inside the handler, like this:

window.onbeforeunload = function(){
    if(!$buttonpressed){
        return "Your changes may not be saved.";
    }
}

当前,它在运行代码时绑定了window.onbeforeunload,因为$buttonpressed在运行时是false……以后再更改都无关紧要,因为您已经绑定了处理程序.另一种选择是使其变得更简单,例如:

Currently it's binding window.onbeforeunload when your code is run because $buttonpressed is false when it runs...it doesn't matter if it changes later since you already bound the handler. An alternative is to make it a bit simpler, like this:

window.onbeforeunload = function(){
    return "Your changes may not be saved.";
}
$j(".Actions input").click(function(){
    window.onbeforeunload = null;
});

这只是删除了click上的处理程序.处理其他提交案件更合适的事件是将事件附加到submit事件,例如:

This just removes the handler on click instead. A more appropriate event to handle other submit cases would be to attach to the submit event, like this:

$j(".myForm").submit(function(){
    window.onbeforeunload = null;
});

这篇关于如果未提交表单,则触发onb​​eforeunload的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆