jQuery 仅绑定到键控,而不是焦点

jQuery bind to keyup only, not focus

本文关键字:焦点 绑定 jQuery      更新时间:2023-09-26

这似乎是一件简单的事情,但谷歌没有为我找到任何东西:

如何仅绑定到文本/值更改事件,不包括获得焦点的输入?即,给定以下内容:

$(function(){
  $('input#target').on('keyup', function(){
    alert('Typed something in the input.');
  });
});

。当用户按 Tab 键进入和退出元素时,无论他们是否实际输入文本,都会触发警报。如何允许用户在不触发事件的情况下通过键盘导航表单,除非他们输入/更改文本字段中的文本?

注意:我正在展示脚本的简化版本,不使用 change 事件的原因是在我的实际代码中,我有一个延迟计时器,以便在用户停止键入一秒钟后发生事件,而无需他们更改焦点来触发事件。

存储值,并在任何关键事件上检查它是否已更改,如下所示:

$(function(){
  $('input#target').on('keyup', function(){
      if ($(this).data('val')!=this.value) {
          alert('Typed something in the input.');
      }
      $(this).data('val', this.value);
  });
});​

小提琴

只需使用 .change 事件即可。

更新:如果需要实时更改通知,则是否必须通过keyup事件,这意味着您需要对处理程序进行编程以忽略那些不会导致值被修改的键。

您可以使用被忽略的键代码白名单来实现这一点,但它可能会变得丑陋:按 Del 会导致值被更改,除非光标位于输入的末尾,在这种情况下它不会,除非输入中恰好有一个选定的范围,在这种情况下它确实如此。

我个人认为如果不是那么"纯粹"的另一种方法是对你的处理程序进行编程,以记住元素的旧值,并且只有在它发生变化时才做出反应。

$(function() {
    // for each input element we are interested in
    $("input").each(function () {
        // set a property on the element to remember the old value,
        // which is initially unknown
        this.oldValue = null;
    }).focus(function() {
        // this condition is true just once, at the time we
        // initialize oldValue to start tracking changes
        if (this.oldValue === null) {
            this.oldValue = this.value;
        }
    }).keyup(function() {
        // if no change, nothing to do
        if (this.oldValue == this.value) {
            return;
        }
        // update the cached old value and do your stuff
        this.oldValue = this.value;
        alert("value changed on " + this.className);
    });
});​

如果您不想直接在 DOM 元素上设置属性(实际上,它没有任何问题),那么您可以在它出现时用 $(this).data("oldValue") 代替this.oldValue。从技术上讲,这将具有使代码变慢的缺点,但我相信没有人会注意到。

看到它的实际效果

这将做到这一点,设置一个自定义属性并检查它:

$('input').focus(function(){ 
    $(this).attr('originalvalue',$(this).val()); 
});
$('input').on('keyup',function(){ 
    if($(this).val()===$(this).attr('originalvalue')) return; 
    alert('he must''ve typed something.'); 
});

警惕多次触发的事件。

这是另一个版本,它清楚地测试输入字段是否为空。

如果输入为空,则不执行该操作。

$(function(){
    $(selector).on('keyup', function(){
        if ($(this).val()!='') {
            alert('char was entered');
        }
    })
});