JS 事件:在文本输入上挂钩值更改事件 [英] JS Events: hooking on value change event on text inputs

查看:38
本文介绍了JS 事件:在文本输入上挂钩值更改事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本输入,其内容由脚本而不是用户更改.所以我想在值改变时触发一个事件.我找不到合适的活动.我什至在 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 突变事件,但它们并没有得到很好的交叉支持-browser,并且无论如何都不要触发表单值,因为这些值不会反映在属性中(由于错误而在 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.

重写设置 value 的脚本部分来调用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆