从输入中删除字符时,如何防止 keyup 事件触发两次?
How can I prevent the keyup event fires twice when remove a character from input?
当从输入中删除预定字符时,keyup 事件会触发两次。我该如何防止这种情况?
HTML
<input type="text" id="search">
JS
var block = {
'ch1': {
'key':'/',
'keycode':'191'
},
'ch2': {
'key':':',
'keycode':'186'
},
'ch3': {
'key':'=',
'keycode':'187'
}
}
$('#search').on('keyup',function(){
console.log(checkChar($(this)));
});
function checkChar($this){
var txt = $this.val(),
flag = true;
for(var i=0; i<txt.length; i++) {
$.each(block,function(k,v){
if (txt[i] === v.key) {
$this.val(txt.slice(0,-1));
flag = false;
return false;
}
});
}
return flag;
}
JSBIN
将event
传递给函数,检查event.shiftKey
,如果条件是true
,return
$('#search').on('keyup',function(e){
var res = checkChar(e, $(this));
if (res !== undefined) {
console.log(res);
};
});
function checkChar(e, $this){
if (e.shiftKey) {
return
};
var txt = $this.val(),
flag = true;
for(var i=0; i<txt.length; i++) {
$.each(block,function(k,v){
if (txt[i] === v.key) {
$this.val(txt.slice(0,-1));
flag = false;
return false;
}
});
}
return flag;
}
当从输入中删除预定字符时,keyup 事件会触发两次。我该如何防止这种情况?
HTML
<input type="text" id="search">
JS
var block = {
'ch1': {
'key':'/',
'keycode':'191'
},
'ch2': {
'key':':',
'keycode':'186'
},
'ch3': {
'key':'=',
'keycode':'187'
}
}
$('#search').on('keyup',function(){
console.log(checkChar($(this)));
});
function checkChar($this){
var txt = $this.val(),
flag = true;
for(var i=0; i<txt.length; i++) {
$.each(block,function(k,v){
if (txt[i] === v.key) {
$this.val(txt.slice(0,-1));
flag = false;
return false;
}
});
}
return flag;
}
JSBIN
将event
传递给函数,检查event.shiftKey
,如果条件是true
,return
$('#search').on('keyup',function(e){
var res = checkChar(e, $(this));
if (res !== undefined) {
console.log(res);
};
});
function checkChar(e, $this){
if (e.shiftKey) {
return
};
var txt = $this.val(),
flag = true;
for(var i=0; i<txt.length; i++) {
$.each(block,function(k,v){
if (txt[i] === v.key) {
$this.val(txt.slice(0,-1));
flag = false;
return false;
}
});
}
return flag;
}