【问题标题】:event.preventDefault() not working on mozillaevent.preventDefault() 在 Mozilla 上不起作用
【发布时间】:2014-09-09 04:43:56
【问题描述】:

我的功能在 Google Chrome 中运行良好,但在 Mozilla 中很糟糕:

JavaScript 代码是:

<script type="text/javascript"> 
    function gid(id) {
        return document.getElementById(id);
    }

    function validate() {
        var x = document.forms["frmSurvey"]["email"].value;
        var atpos = x.indexOf("@");
        var dotpos = x.lastIndexOf(".");            

        if((gid('0_stars').checked==true) || (gid('1_stars').checked==true) || (gid('2_stars').checked==true) || (gid('3_stars').checked==true) || (gid('4_stars').checked==true)) {
            if((gid('comment').value != '') && (gid('email').value != '') && (gid('name').value != '')) {
                if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
                    alert("Not a valid e-mail address. Please write a valid e-mail address!");
                    return false;
               } else {
                    document.getElementById("frmSurvey").submit();
                }
            }
            else {
                alert('You haven`t completed the mandatory fields. Please make sure that you complete the form corectly! Thank you!');
                return false;
            }
        }
        else {
            alert('You haven`t completed the mandatory fields. Please make sure that you complete the form corectly! Thank you!');
            return false;
        }
    }       
</script>

形式是:

<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post" id="frmSurvey" onsubmit="event.preventDefault(); validate();"> 
    ...
    ...
    ...
</form>

有什么方法可以用另一个函数替换这个函数吗?我已经尝试过 return false;但是它根本不提交!

【问题讨论】:

  • 不知道这是否有帮助,但我通常将事件传递给函数。在你的情况下 validate(event) { event.preventDefault() } onsubmit="validate(event)"跨度>
  • 我建议从表单标签中删除 onsubmit,而是在提交按钮本身上创建一个事件监听器,例如 $("#mysubmitid").click(function(){ validate(); });
  • 你试过 event.stopPropagation 吗?

标签: javascript html google-chrome mozilla


【解决方案1】:

return true 添加到validate 的末尾。

然后改变:

onsubmit="event.preventDefault(); validate();"

...到:

onsubmit="return validate();"

这将导致表单仅在经过验证后才提交。

编辑

完成此操作后,您可以从validate() 中删除此行:

document.getElementById("frmSurvey").submit();

【讨论】:

    【解决方案2】:

    尝试删除表单元素中的 onsubmit 并将其添加到您的 js 文件中。

     $('#frmSurvey').submit(function( event ) {
          event.preventDefault();
     });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-17
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 2016-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多