jQuery只绑定到keyup,而不是焦点。

时间:2022-02-25 19:16:32

This seems like a simple thing but google hasn't turned up anything for me:

这看起来很简单,但是谷歌并没有为我找到任何东西:

How can I bind to a text / value change event only, excluding an input gaining focus? Ie, given the following:

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

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

...the alert would be triggered when the user tabs in and out of an element, whether they actually input text or not. How can you allow a user to keyboard navigate through the form without triggering the event unless they input/change the text in the text field?

…无论用户是否输入文本,当用户在元素内和元素外制表符时,都会触发警报。如果用户不输入/更改文本字段中的文本,那么您如何允许用户在不触发事件的情况下通过表单进行导航?

Note: I'm showing a simplified version of a script, the reason for not using the change event is that in my real code I have a delay timer so that the event happens after the user stops typing for a second, without them having to change focus to trigger the event.

注意:我给一个简化版本的脚本,不使用改变事件的原因是,在我真正的代码我已经延迟计时器,事件发生后的用户停止打字,没有他们不得不改变焦点来触发事件。

4 个解决方案

#1


6  

Store the value, and on any key event check if it's changed, like so:

存储该值,并在任何关键事件检查它是否被更改,如:

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

FIDDLE

小提琴

#2


4  

Simply use the .change event.

只需使用.change事件。

Update: If you want live change notifications then do you have to go through the keyup event, which means that you need to program your handler to ignore those keys that will not result in the value being modified.

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

You can implement this with a whitelist of key codes that are ignored, but it could get ugly: pressing Del results in the value being changed, unless the cursor is positioned at the end of the input in which case it does not, unless there happens to be a selected range in the input in which case it does.

可以实现这个白名单关键代码的忽视,但它能丑:紧迫Del导致的值被改变,除非光标定位在结束的输入在这种情况下,它不会,除非碰巧有一个选择范围的输入在这种情况下它。

Another way which I personally find more sane if not as "pure" is to program your handler to remember the old value of the element and only react if it has changed.

另一种我个人认为更理智的方式,如果不是“纯粹”,就是让你的处理程序记住元素的旧值,并且只在它发生变化时做出反应。

$(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);
    });
});​

If you do not want to set properties directly on the DOM element (really, there's nothing wrong with it) then you could substitute $(this).data("oldValue") for this.oldValue whenever it appears. This will technically have the drawback of making the code slower, but I don't believe anyone will notice.

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

See it in action.

看它的实际应用。

#3


1  

This will do it, set a custom attribute and check against that:

它会这样做,设置一个自定义属性并对其进行检查:

$('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.'); 
});

Be wary of events firing multiple times.

要警惕多次触发的事件。

#4


0  

Here is another version that plainly tests if the input field is empty.

下面是另一个版本,它可以直接测试输入字段是否为空。

If the input is empty then the action is not performed.

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

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

#1


6  

Store the value, and on any key event check if it's changed, like so:

存储该值,并在任何关键事件检查它是否被更改,如:

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

FIDDLE

小提琴

#2


4  

Simply use the .change event.

只需使用.change事件。

Update: If you want live change notifications then do you have to go through the keyup event, which means that you need to program your handler to ignore those keys that will not result in the value being modified.

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

You can implement this with a whitelist of key codes that are ignored, but it could get ugly: pressing Del results in the value being changed, unless the cursor is positioned at the end of the input in which case it does not, unless there happens to be a selected range in the input in which case it does.

可以实现这个白名单关键代码的忽视,但它能丑:紧迫Del导致的值被改变,除非光标定位在结束的输入在这种情况下,它不会,除非碰巧有一个选择范围的输入在这种情况下它。

Another way which I personally find more sane if not as "pure" is to program your handler to remember the old value of the element and only react if it has changed.

另一种我个人认为更理智的方式,如果不是“纯粹”,就是让你的处理程序记住元素的旧值,并且只在它发生变化时做出反应。

$(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);
    });
});​

If you do not want to set properties directly on the DOM element (really, there's nothing wrong with it) then you could substitute $(this).data("oldValue") for this.oldValue whenever it appears. This will technically have the drawback of making the code slower, but I don't believe anyone will notice.

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

See it in action.

看它的实际应用。

#3


1  

This will do it, set a custom attribute and check against that:

它会这样做,设置一个自定义属性并对其进行检查:

$('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.'); 
});

Be wary of events firing multiple times.

要警惕多次触发的事件。

#4


0  

Here is another version that plainly tests if the input field is empty.

下面是另一个版本,它可以直接测试输入字段是否为空。

If the input is empty then the action is not performed.

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

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