点击http://jsfiddle.net/qPvch/291/查看结果。我在stackoverflow的一个答案中发现了这个代码,我对它进行了一点编辑。我只想限制字母的数量,我成功地做到了,但达到限制后,我不能退格或键入任何内容。救命,谢谢。
var maxWords = 3;
jQuery('#txt1').keypress(function() {
var $this, wordcount;
$this = $(this);
wordcount = $this.val().length;
if (wordcount > maxWords) {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Max 3 letters
<input type="text" id="txt1"/>
您可以测试输入的内容,例如是否为字符。例如:
var maxWords = 2;
jQuery('#txt1').keypress(function(e) {
var $this, wordcount;
var code = e.keyCode || e.which;
var char = String.fromCharCode(code)
$this = $(this);
wordcount = $this.val().length;
if (wordcount > maxWords && char.match(/[a-z]/i)) {
return false;
}
});
获取密钥代码,将其转换为字符,然后对所有字母进行测试(不区分大小写)。你可以根据自己的需要添加匹配字符串。
请参阅此Fiddle