JS事件:挂起文本输入上的值更改事件 [英] JS Events: hooking on value change event on text inputs
问题描述
我有一个文本输入,其内容是由脚本而不是用户改变的。所以我想在值发生变化时触发事件。我找不到合适的事件。
我甚至在StackOverflow上发现了 ,但它不是我正在寻找的解决方案。
I have a text input whose content is changed by a script not by user. So I would want to fire an event when the value changes. I can't find a suitable event for that. I even found this on StackOverflow, but it is not the solution I'm looking for.
如何使这个工作与jQuery和一个文本输入,其值设置为这样:
How to make this work with jQuery and a text input where the value is set like this:
myTextControl.value = someValue
这里我想启动一个事件来看新值。
Here I want to fire an event to see the new value.
推荐答案
我找不到合适的事件。
I can't find a suitable event for that.
是的,没有一个。
有 DOM突变事件,但是他们不支持跨浏览器,并且不要为表单值触发,因为这些不会反映在属性中(除了在IE中由于错误)。
There are DOM Mutation Events, but they aren't supported well cross-browser, and don't fire for form values anyway as those aren't reflected in attributes (except in IE due to a bug).
仅在Mozilla中,JavaScript watch 可以在value属性上设置来捕获脚本的更改。仅在IE中,JScript onpropertychange 处理程序可以设置为捕获脚本和用户驱动的更改。在其他浏览器中,您必须使用自己的间隔轮询器来查找更改。
In Mozilla only, a JavaScript watch could be set on the value property to catch scripted changes. In IE only, a JScript onpropertychange handler could be set to catch both scripted and user-driven changes. In other browsers you would have to use your own interval poller to look for changes.
function watchProperty(obj, name, handler) {
if ('watch' in obj) {
obj.watch(name, handler);
} else if ('onpropertychange' in obj) {
name= name.toLowerCase();
obj.onpropertychange= function() {
if (window.event.propertyName.toLowerCase()===name)
handler.call(obj);
};
} else {
var o= obj[name];
setInterval(function() {
var n= obj[name];
if (o!==n) {
o= n;
handler.call(obj);
}
}, 200);
}
}
watchProperty(document.getElementById('myinput'), 'value', function() {
alert('changed!');
});
这是非常不满意的。它不会响应Mozilla中的用户驱动的更改,它只允许IE中每个对象的一个监视属性,而在其他浏览器中,处理函数将在执行流程中稍后调用。
This is highly unsatisfactory. It won't respond to user-driven changes in Mozilla, it allows only one watched property per object in IE, and in other browsers the handler function will get called much later in execution flow.
重写脚本的部分肯定更好,设置值
来调用setValue包装函数,可以监视要捕获的更改。
It's almost certainly better to rewrite the parts of script that set value
to call a setValue wrapper function instead, that you can monitor for changes you want to trap.
这篇关于JS事件:挂起文本输入上的值更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!