因此,当用户在输入字段中输入5个字符时,我会触发一个函数。
但是,每当我在完成5之后放置其他字符时,它就会继续触发事件。
如何防止这种情况发生?
$(function(){
var $zipEntry = $('#zipEntry').bind('keyup',function(event) { //bind to key up, doesn't require
//make sure that there are 5 numbers... or length = 5 since numeric only input
var $this = $(this); // cache $(this)
if ($this.val().length == 5){ // use cached
console.log("There are 5 characters!!");
$this.trigger('zipEntered');
}
});
答案 0 :(得分:1)
如果我理解正确,你需要使用“更大或相等”而不是“相等”
if ($this.val().length >= 5){
另外,为什么在变量名中使用$?
答案 1 :(得分:1)
在听完事件后尝试取消绑定事件。
if ($this.val().length == 5){
console.log("There are 5 characters!!");
$this.trigger('zipEntered');
$('#zipEntry').unbind('keyup');
}
答案 2 :(得分:1)
不能在源头纠正问题吗?在输入字段上放一个maxlength?