javascript 检测输入类型文本的程序更改
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16013024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect programmatic changes on input type text
提问by Zo72
Is there a way to get informed when a script changes the value of an input type text.
有没有办法在脚本更改输入类型文本的值时获得通知。
I have
我有
<input id='test' type='text' />
and a script
和一个脚本
document.getElementById('test').value = 'bbb';
I want to be notified of the change of the text.
我想收到有关文本更改的通知。
I know I could be notified by keydown,keyup, onblur etcetera (which works if I am trying to track user typing) but what about if the change is done programmatically ?
我知道我可以通过 keydown、keyup、onblur 等来通知我(如果我试图跟踪用户输入,这会起作用)但是如果更改是以编程方式完成的呢?
Many thanks
非常感谢
p.s. No JQuery please or if jquery does it can somebody explain how it achieves it.
ps请不要JQuery,或者如果jquery可以,有人可以解释它是如何实现的。
采纳答案by MaxArt
If you're dealing with a modern browser, you can try with something like this:
如果您使用的是现代浏览器,则可以尝试以下操作:
var input = document.getElementById('test');
input._value = input.value;
Object.defineProperty(input, "value", {
get: function() {return this._value;},
set: function(v) {
// Do your stuff
this._value = v;
}
});
This solution is good if you actually don't expect any user input (i.e., hidden type input fields), because it's extremely destructiveof the DOM basic functionality. Keep that in mind.
如果您实际上不希望有任何用户输入(即隐藏类型的输入字段),则此解决方案很好,因为它对DOM 基本功能具有极大的破坏性。记住这一点。
回答by Félix Gagnon-Grenier
I find the simplest way is to actually trigger the event manually:
我发现最简单的方法是手动触发事件:
document.getElementById('test').value = 'bbb';
var evt = new CustomEvent('change');
document.getElementById('test').dispatchEvent(evt);
Just listening to the change
event is error-prone when the value is changed programmatically. But since you are changing the value, add two lines and fire the change event, with a CustomEvent.
change
当以编程方式更改值时,仅侦听事件很容易出错。但由于您正在更改值,添加两行并使用CustomEvent触发更改事件。
then you'll be able to catch this change
event, either inline:
那么你将能够捕捉到这个change
事件,无论是内联的:
<input id="test" onchange="console.log(this)">
or with a listener:
或与听众:
document.getElementById('test').addEventListener('change',function(event) {
console.log(event.target);
});
this have the advantage that if you have an input which can be changed by the user, you can catch both those events (from the user or the script)
这样做的好处是,如果您有一个可由用户更改的输入,则可以捕获这两个事件(来自用户或脚本)
this however depends on the fact that you are yourself programmatically changing the value of the input. If you are using libraries (such as datepickr) that change the values of your inputs you may have to get in the code and add those two lines at the right place.
然而,这取决于您自己以编程方式更改输入值的事实。如果您使用的库(例如datepickr)会更改您的输入值,您可能必须输入代码并在正确的位置添加这两行。