我在使用 JS 进行文本框验证时遇到问题。这是我的来源:
$(document).ready(function() {
$("#letnd").keypress(function(e) {
var regex = new RegExp("^[a-zA-Z]+$");
var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (!regex.test(key)) {
e.preventDefault();
return false;
}
});
$("#letnb").keypress(function(e) {
var regex = new RegExp("^[a-zA-Z]+$");
var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (!regex.test(key)) {
e.preventDefault();
return false;
}
});
});
<input id="letnd" type="text" name="txtnd" />
<input id="letnb" type="text" name="txtnb" />
在其他浏览器中,此代码可以正常工作。但是为什么当我在 Mozilla 中打开它时,文本框无法使用 backspace 和 del ?
最佳答案
当您按下退格键或箭头以及其他一些键时,其他浏览器不会触发按键事件,而 FF 会触发按键事件。不知道谁在那儿。如果将 keypress 事件替换为 keydown,则每个浏览器都将充当 FF。
根据specs :
The keypress event is traditionally associated with detecting a character value rather than a physical key, and might not be available on all keys in some configurations.
还值得一提的是keypressEvent
现已在 DOM3 中弃用。 beforeinput
应该使用,但尚未在任何主要浏览器中实现,主要是因为规范对此尚不清楚。 related chromium bug report .
但是,您可以做的是检查 <input>
的值keyup
上的元素如果有一些禁用字符,请将其删除。一个小警告是禁止的字符将在被删除之前出现:
$(document).ready(function() {
$("#letnd").keyup(validate);
$("#letnb").keyup(validate);
});
function validate(e) {
var regex = new RegExp("[^a-zA-Z]","g");
var string = this.value;
var match = string.match(regex);
if (match) {
this.value = this.value.replace(regex, '');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="letnd" type="text" name="txtnd" />
<input id="letnb" type="text" name="txtnb" />
关于javascript - 我无法在文本框中使用退格键和删除键(Mozilla),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31804855/