SNa*_*Nag 128 jquery events textbox
我发现文本框上的jQuery更改事件在我单击文本框之外时才会触发.
HTML:
<input type="text" id="textbox" />
Run Code Online (Sandbox Code Playgroud)
JS:
$("#textbox").change(function() {alert("Change detected!");});
Run Code Online (Sandbox Code Playgroud)
请参阅JSFiddle上的演示
我的应用程序要求在文本框中的每个字符更改时触发事件.我甚至试过使用keyup代替......
$("#textbox").keyup(function() {alert("Keyup detected!");});
Run Code Online (Sandbox Code Playgroud)
...但是已知的事实是,右键单击并粘贴时不会触发keyup事件.
任何解决方法?让两个听众都会引起任何问题吗?
Pet*_*tah 291
绑定到这两个事件是典型的方法.您还可以绑定到粘贴事件.
您可以绑定到多个事件,如下所示:
$("#textbox").on('change keyup paste', function() {
console.log('I am pretty sure the text box changed');
});
Run Code Online (Sandbox Code Playgroud)
如果你想对它迂腐,你还应该绑定到mouseup以满足拖动文本的需要,并添加一个lastValue
变量以确保文本实际上发生了变化:
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');
}
});
Run Code Online (Sandbox Code Playgroud)
如果你想要super duper
迂腐,那么你应该使用间隔计时器来满足自动填充,插件等:
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);
Run Code Online (Sandbox Code Playgroud)
A. *_*lff 83
在现代浏览器中,您可以使用以下input
事件:
$("#textbox").on('input',function() {alert("Change detected!");});
Run Code Online (Sandbox Code Playgroud)