用户在文本框中输入内容后,是否有可能(跨浏览器兼容)取消用户已经输入的键盘按键呢?
目前我的代码是在显示按键后编辑文本框的值:
$('.number').keypress(function() {
this.value = this.value.replace(/[^0-9\.]/g, '');
});
用户在文本框中输入内容后,是否有可能(跨浏览器兼容)取消用户已经输入的键盘按键呢?
目前我的代码是在显示按键后编辑文本框的值:
$('.number').keypress(function() {
this.value = this.value.replace(/[^0-9\.]/g, '');
});
$('.number').keypress(function() {
if ( this.value == 'foobar' ){
// "Cancel" keystroke
return false;
}
this.value = this.value.replace(/[^0-9\.]/g, '');
});
已解决(并更新)
抱歉,我没有测试最明显的选项 - 但它起作用了:
$('.number').keypress(function(event) {
return /[0-9\.]/.test(String.fromCharCode(event.keyCode));
});
test()
函数来简化代码,像这样:/[^0-9\.]/.test(String.fromCharCode(event.keyCode))
。由于已经使用了 return false;
,所以无需进行替换或赋值操作。由于只测试单个按键事件,因此也不需要使用全局标识符 g
。 - user113716
this.value
中的被禁止的值。您正在对整个this.value
进行精确匹配测试。 - user113716if()
语句返回true
,replace()
就不会触发。因为你正在针对this.value
进行测试,这是一个至关重要的部分。 - user113716