preventDefault无法在Firefox中运行

时间:2015-02-25 18:16:39

标签: jquery html

我有这段代码:

    <html>
        <head>
        </head>
        <body>
        <input type="text" class="additionalName">
        <span class="additionalNameError"></span>
        <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
  $(function(){
    $('.additionalName').on("keypress",function (f) {
                                if (!alphaOnly(f)) {
                                    $(".additionalNameError").show().html("&nbsp;You must use text only - see <a href='#name_rules'>name rules</a>").fadeOut("slow").delay(10000);
                                    f.preventDefault();
                                    return false; 
                                    //event.preventDefault();
                                    //return false;
                                }
                            });

                            function alphaOnly(e) {
                                var inp = String.fromCharCode(e.keyCode);
                                if (/[a-zA-Z-']/.test(inp)) return true;
                                else return false;
                            };
    });
        </script>
        </body>
        </html>

该代码适用于Chrome,但不适用于Firefox。任何建议都非常感谢。我尝试在event方法中添加preventDefault变量,但似乎没有任何效果

2 个答案:

答案 0 :(得分:0)

出于某种原因,当你使用keypress时,firefox总是返回按下的键为0(意味着你的函数将始终触发)。如果您将其更改为在keyup上触发,则可以正常使用。

答案 1 :(得分:0)

根据jQuery文档,建议将event.which用于关键事件。

  

event.which属性规范化event.keyCode和event.charCode。建议观看event.which键盘输入键。

参考:event.which docs

相关问题