【问题标题】:How can I prevent the keyup event fires twice when remove a character from input?从输入中删除字符时,如何防止 keyup 事件触发两次?
【发布时间】:2017-01-13 12:59:06
【问题描述】:

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

【问题讨论】:

  • 问题是当你松开shift键时,也会产生一个keyup事件。尝试过滤您感兴趣的键。

标签: javascript jquery preventdefault keyup onkeyup


【解决方案1】:

event传递给函数,检查event.shiftKey,如果条件是truereturn

$('#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;


}

【讨论】:

  • 这正是我想要的。谢谢
猜你喜欢
  • 1970-01-01
  • 2021-11-25
  • 2015-03-18
  • 2019-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-22
相关资源
最近更新 更多