HTML:监听输入的*所有*更改,而不仅仅是键盘驱动的更改?
例如,如果我有这样的输入:
<input id="myInput" type="text" />
当以编程方式更改值时,如何通知我(例如,由于 $("#myInput").val("new value") )?
示例: http://jsfiddle.net/2ax9y/
编辑:请注意,问题是询问如何监听更改,而不是“如何手动分派更改”。我很清楚我可以手动分派更改事件,但我试图避免这种情况。
For example, if I've got an input like this:
<input id="myInput" type="text" />
How can I be notified when the value is changed programatically (for example, as a result of $("#myInput").val("new value")
)?
An example: http://jsfiddle.net/2ax9y/
Edit: please note, the question is asking how to listen for changes, not “how to manually dispatch changes”. I'm well aware that I can manually dispatch change events, but I'm trying to avoid that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以更改
$
原型,以便在调用val(value)
时始终触发change()
事件:You can change the
$
prototype to always triggerchange()
events wheneverval(value)
is called:触发更改: http://jsfiddle.net/maniator/2ax9y/1/
一点不同的是: http://jsfiddle.net/maniator/2ax9y/2/
Trigger the change: http://jsfiddle.net/maniator/2ax9y/1/
A little differently: http://jsfiddle.net/maniator/2ax9y/2/
您无法可靠地订阅输入元素上的每个更改,但您可以检查自上次检查以来是否发生了更改,并在某个所需的时间粒度内执行此操作。
创建一个检查器函数并以您所需的时间粒度循环它 - 100 毫秒是一个好的开始,请根据您的需要进行调整。
假设的未经测试的实现:
You can't reliably subscribe to every change on an input element, but you can check if there has been a change since you last checked and do that within some desired time granularity.
Make a checker function and loop it with your desired time granularity—100ms is a good start, adjust to your needs.
Hypothetical untested implementation:
我不认为这是变革事件的固有能力。当您以编程方式更改值时,可以手动触发更改事件。
I don't think this is an inherent ability of the change event. You could manually trigger the change event when you programmatically change the value.