当从输入框中删除字符时,如何防止 keyup 事件触发两次?

4

当从输入中删除预定字符时,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

https://jsbin.com/mirocepiqo/1/edit?html,js,output


2
问题在于当你释放Shift键时,也会生成一个keyup事件。尝试过滤你感兴趣的按键。 - GOTO 0
1个回答

2

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;


}

这正是我想要的。谢谢。 - midstack

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接