检测 jQuery 中的输入变化? [英] Detecting input change in jQuery?
问题描述
当在 input
上使用 jquery .change
时,事件只会在输入失去焦点时触发
When using jquery .change
on an input
the event will only be fired when the input loses focus
就我而言,我需要在输入值更改后立即调用服务(检查值是否有效).我怎么能做到这一点?
In my case, I need to make a call to the service (check if value is valid) as soon as the input value is changed. How could I accomplish this?
推荐答案
更新说明和示例
示例:http://jsfiddle.net/pxfunc/5kpeJ/
方法一、input
事件
Method 1. input
event
在现代浏览器中使用 input
事件.当用户在文本字段中键入、粘贴、撤消,基本上任何时候值从一个值更改为另一个值时,都会触发此事件.
In modern browsers use the input
event. This event will fire when the user is typing into a text field, pasting, undoing, basically anytime the value changed from one value to another.
在 jQuery 中这样做
In jQuery do that like this
$('#someInput').bind('input', function() {
$(this).val() // get the current value of the input field.
});
从 jQuery 1.7 开始,将 bind
替换为 on
:
starting with jQuery 1.7, replace bind
with on
:
$('#someInput').on('input', function() {
$(this).val() // get the current value of the input field.
});
方法二.keyup
事件
Method 2. keyup
event
对于较旧的浏览器,使用 keyup
事件(一旦键盘上的一个键被释放,这个事件就会触发,这个事件可能会产生一种误报,因为当w"被释放时,输入值被改变并且 keyup
事件被触发,而且当shift"键被释放时 keyup
事件被触发但没有对输入进行任何更改.)如果用户右键单击并从上下文菜单中粘贴此方法也不会触发:
For older browsers use the keyup
event (this will fire once a key on the keyboard has been released, this event can give a sort of false positive because when "w" is released the input value is changed and the keyup
event fires, but also when the "shift" key is released the keyup
event fires but no change has been made to the input.). Also this method doesn't fire if the user right-clicks and pastes from the context menu:
$('#someInput').keyup(function() {
$(this).val() // get the current value of the input field.
});
方法 3. 定时器(setInterval
或 setTimeout
)
Method 3. Timer (setInterval
or setTimeout
)
要绕过keyup
的限制,您可以设置一个计时器来定期检查输入的值以确定值的变化.您可以使用 setInterval
或 setTimeout
来执行此计时器检查.请参阅此 SO 问题的标记答案:jQuery 文本框更改事件或使用 focus 的工作示例查看小提琴
和 blur
事件用于启动和停止特定输入字段的计时器
To get around the limitations of keyup
you can set a timer to periodically check the value of the input to determine a change in value. You can use setInterval
or setTimeout
to do this timer check. See the marked answer on this SO question: jQuery textbox change event or see the fiddle for a working example using focus
and blur
events to start and stop the timer for a specific input field
这篇关于检测 jQuery 中的输入变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!