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

查看:28
本文介绍了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?

推荐答案

绑定到两个事件是典型的方法.您也可以绑定到 paste 事件.

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天全站免登陆