我想忽略电话输入中的某些字符,以便数据库只有数字。我知道我可以在服务器端(使用 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;
});
我只是不明白为什么。提前感谢您对这个主题的任何启发..
最佳答案
我强烈建议不要更改用户的输入或以其他方式阻止他们在输入内容时进行输入。它令人困惑并导致糟糕的用户体验。
理想情况下,您应该保留服务器端验证,然后使用如下 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;
关于javascript - 忽略按键上的输入字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15302746/