梦里花落0921
您只需使用一个简单的JavaScript正则表达式来测试纯数字字符:/^[0-9]+$/.test(input);如果输入为数字,则返回true;如果输入不是,则返回false。或者对于事件密钥,只需在下面简单使用: // Allow: backspace, delete, tab, escape, enter, ctrl+A and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
var charValue = String.fromCharCode(e.keyCode)
, valid = /^[0-9]+$/.test(charValue);
if (!valid) {
e.preventDefault();
}