【问题标题】:jQuery: fire keyup on all document excluding one input text fieldjQuery:在除一个输入文本字段之外的所有文档上触发 keyup
【发布时间】:2013-12-09 14:39:10
【问题描述】:

我有一个

$(document).keyup(function(e) {
  //some code is here
});

代码,按预期工作:当我按下键盘上的任意键时它会触发。 我希望它触发,但不是当光标位于

<input type="text" id="excludeMeFromFiring">

在页面上。

如何修改上面的代码以在输入带有特殊 id 的输入文本字段时排除触发?因此,如果光标在输入文本字段中,它不会触发。

谢谢。

【问题讨论】:

    标签: javascript jquery input keyup jquery-1.9


    【解决方案1】:

    keyup 函数中很容易做到这一点:

    $(document).keyup(function(e) {
        if ($(e.target).closest("#excludeMeFromFiring")[0]) {
            return;
        }
    
        // It's not that element, handle it
    });
    

    这是一般情况;因为input 元素中不能有任何元素,所以你可以只使用e.target.id 而不是closest

    $(document).keyup(function(e) {
        if (e.target.id === "excludeMeFromFiring") {
            return;
        }
    
        // It's not that element, handle it
    });
    

    只要元素内部可以包含其他元素,我就会使用closest

    【讨论】:

      【解决方案2】:

      试试

      $(document).keyup(function (e) {
          if(e.target.id === 'excludeMeFromFiring'){
              console.log('no');
          }else{
              console.log('hi');
          }
      });
      

      $(document).keyup(function (e) {
          if(e.target.id !== 'excludeMeFromFiring'){
             console.log('hi');
          }
      });
      

      【讨论】:

        【解决方案3】:

        另一个例子:

        $('#excludeMeFromFiring').keyup(function(e) {
            e.stopPropagation();
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-04-13
          • 2021-09-14
          • 1970-01-01
          • 2023-03-24
          • 1970-01-01
          相关资源
          最近更新 更多