jQuery文本框更改事件不会触发,直到文本框失去焦点? [英] jQuery textbox change event doesn't fire until textbox loses focus?

查看:157
本文介绍了jQuery文本框更改事件不会触发,直到文本框失去焦点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现文本框上的jQuery更改事件不会触发,直到我点击文本框外。

I found that jQuery change event on a textbox doesn't fire until I click outside the textbox.

HTML:

<input type="text" id="textbox" />

JS:

$("#textbox").change(function() {alert("Change detected!");});

请参阅在JSFiddle上演示

我的应用程序需要在文本框中的每个字符更改触发事件。我甚至尝试使用keyup ...

My application requires the event to be fired on every character change in the textbox. I even tried using keyup instead...

$("#textbox").keyup(function() {alert("Keyup detected!");});

...但这是一个已知的事实,keyup事件没有触发右键单击,粘贴。

...but it's a known fact that the keyup event isn't fired on right-click-and-paste.

任何解决方法?是否有两个听众会导致任何问题?

Any workaround? Is having both listeners going to cause any problems?

推荐答案

绑定到这两个事件是这样做的典型方式。您也可以绑定到粘贴事件。

Binding to both events is the typical way to do it. You can also bind to the paste event.

您可以绑定到这样的多个事件:

You can bind to multiple events like this:

$("#textbox").on('change keyup paste', function() {
    console.log('I am pretty sure the text box changed');
});

如果你想嘲笑它,你也应该绑定到mouseup,以适应拖动文本,并添加一个 lastValue 变量,以确保文本实际上改变了:

If you wanted to be pedantic about it, you should also bind to mouseup to cater for dragging text around, and add a lastValue variable to ensure that the text actually did change:

var lastValue = '';
$("#textbox").on('change keyup paste mouseup', function() {
    if ($(this).val() != lastValue) {
        lastValue = $(this).val();
        console.log('The text box really changed this time');
    }
});

如果你想要成为 super duper 那么你应该使用间隔计时器来满足自动填充,插件等:

And if you want to be super duper pedantic then you should use an interval timer to cater for auto fill, plugins, etc:

var lastValue = '';
setInterval(function() {
    if ($("#textbox").val() != lastValue) {
        lastValue = $("#textbox").val();
        console.log('I am definitely sure the text box realy realy changed this time');
    }
}, 500);

这篇关于jQuery文本框更改事件不会触发,直到文本框失去焦点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆