9

我想忽略手机输入中的某些字符,以便数据库只有数字。我知道我可以在服务器端(使用 PHP)轻松做到这一点,但我试图更好地理解 js 事件。我的问题是:

如果我有基本输入:

var phoneInput = document.getElementById("phoneInput");

我可以使用“onkeydown”添加一个事件监听器,效果很好

phoneInput.onkeydown = function(e){
  var c = String.fromCharCode(e.keyCode);
  var patt = /\d/;
  if(!patt.test(c)) return false;
};

但是如果我尝试使用“addEventListener”做同样的事情,返回 false 似乎什么都不做

phoneInput.addEventListener("keydown",function(e){
  var c = String.fromCharCode(e.keyCode);
  var patt = /\d/;
  if(!patt.test(c)) return false;
});

我只是不明白为什么。提前感谢您可以照亮主题的任何光线。

4

2 回答 2

14

我强烈建议不要更改用户的输入或以其他方式阻止他们在执行操作时输入内容。它令人困惑并导致糟糕的用户体验。

理想情况下,您应该保留服务器端验证,然后使用 HTML5 功能,例如:

<input type="number" /> Allows only numbers
<input type="text" pattern="[0-9. -]*" /> Allows numbers, spaces, periods and hyphens
<input type="text" required /> Specifies a required field

现代浏览器将阻止提交表单并向用户显示有用的错误消息(您可以使用title属性对其进行自定义)。

但是,作为一般参考,return false;并不一定会取消该事件。为此,您应该使用以下命令:

// if you haven't already:
e = e || window.event;
// to cancel the event:
if( e.preventDefault) e.preventDefault();
return false;
于 2013-03-08T20:36:49.313 回答
5

我必须为我正在从事的项目做类似的事情。我就是这样做的。

// prevent users from typing alpha/ symbol characters on select fields
$("#modal-region").on("keydown", "#markdown, #sku", function(e) {

    var key = e.which;
    // when a keydown event occurs on the 0-9 keys the value 
    // of the "which" property is between 48 - 57 
    // therefore anything with a value greater than 57 is NOT a numeric key

    if ( key > 57) {
        e.preventDefault();

    } else if (key < 48) {

    // we don't want to disable left arrow (37), right arrow (39), delete (8) or tab (9)
    // otherwise the use cannot correct their entry or tab into the next field!

        if (key != 8 && key != 9 && key != 37 && key != 39 ) {
            e.preventDefault();
        }
    }

});
于 2014-07-24T20:57:05.610 回答