如何防止"您确定要离开此页面吗?" 表格提交时提醒?

ash*_*ram 3 html javascript

我有一个简单的html表单,其中包含很少的字段.

我想确保用户在尝试离开页面时收到警告消息.所以我在页面上添加了脚本,只要用户试图离开此页面,该脚本就会运行.

但是当用户尝试提交表单时,我也收到此警报消息.当用户保存表单时,我不想要此警报消息.

请帮忙.

下面是一些示例代码.

<html>
    <head>

    <script>
        function verifyexit() { return 'Are you sure ?'; }           window.onbeforeunload = verifyexit;
    </script>       
</head>
<body>
        Go to <a href="b.html"> another page </a> 
        <form action="c.html">
            name : <input type="text" name="name" value=""/> <br>
            email : <input type="text" name="email" value=""/> <br>
            <input type="submit" value="save"/>
        </form>
</body> 
Run Code Online (Sandbox Code Playgroud)

sha*_*eef 6

stackoverflow参考

打开它:

window.onbeforeunload = "Are you sure you want to leave?";
Run Code Online (Sandbox Code Playgroud)

要关闭它:

window.onbeforeunload = null;
Run Code Online (Sandbox Code Playgroud)

请记住,这不是正常事件 - 您无法以标准方式绑定它.

要检查值?这取决于您的验证框架.

在jQuery中,这可能是(非常基本的例子):

$('input').change(function() {
    if( $(this).val() != "" )
        window.onbeforeunload = "Are you sure you want to leave?";
});
Run Code Online (Sandbox Code Playgroud)

使用JQuery这个东西很容易做到.因为你可以绑定到集合.

它不足以进行onbeforeunload,你只想触发导航,如果有人开始编辑东西.

要在Chrome和Safari中使用,您必须这样做

window.onbeforeunload = function (e) {
    e = e || window.event;

    var msg = "Sure you want to leave?";

    // For IE and Firefox prior to version 4
    if (e) {
        e.returnValue = msg;
    }

    // For Safari
    return msg;
};
Run Code Online (Sandbox Code Playgroud)


这是参考的一般规则

window.onbeforeunload = function (e) {
  e = e || window.event;

  // For IE<8 and Firefox prior to version 4
  if (e) {
    e.returnValue = 'Any string';
  }

  // For Chrome, Safari, IE8+ and Opera 12+
  return 'Any string';
};
Run Code Online (Sandbox Code Playgroud)

参考:https://developer.mozilla.org/en/DOM/window.onbeforeunload

  • `你不能以标准方式绑定它`请澄清。 (2认同)