Javascript JS 事件:在文本输入上挂钩值更改事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1847893/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 21:35:55  来源:igfitidea点击:

JS Events: hooking on value change event on text inputs

javascriptjqueryeventsinput

提问by Esteban Feldman

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.

我有一个文本输入,其内容由脚本而不是用户更改。所以我想在值改变时触发一个事件。我找不到合适的活动。我什至在 StackOverflow 上找到了这个,但这不是我正在寻找的解决方案。

How to make this work with jQuery and a text input where the value is set like this:

如何使用 jQuery 和文本输入使其工作,其中值设置如下:

myTextControl.value = someValue

Here I want to fire an event to see the new value.

在这里,我想触发一个事件以查看新值。

回答by bobince

I can't find a suitable event for that.

我找不到合适的活动。

Yeah, there isn't one.

是的,没有一个。

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).

DOM Mutation Events,但它们不受跨浏览器的良好支持,并且无论如何都不会触发表单值,因为这些值没有反映在属性中(由于错误而在 IE 中除外)。

In Mozilla only, a JavaScript watchcould be set on the value property to catch scripted changes. In IE only, a JScript onpropertychangehandler 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.

仅在 Mozilla 中,可以在 value 属性上设置JavaScript监视以捕获脚本更改。仅在 IE 中,可以设置JScript onpropertychange处理程序来捕获脚本化和用户驱动的更改。在其他浏览器中,您必须使用自己的间隔轮询器来查找更改。

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!');
});

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.

这是非常不令人满意的。它不会响应 Mozilla 中用户驱动的更改,它只允许 IE 中的每个对象一个被监视的属性,而在其他浏览器中,处理程序函数将在执行流程中调用很晚。

It's almost certainly better to rewrite the parts of script that set valueto call a setValue wrapper function instead, that you can monitor for changes you want to trap.

几乎可以肯定,重写设置value为调用 setValue 包装函数的脚本部分会更好,您可以监视要捕获的更改。

回答by jitter

You can add a normal event listener to your input field like so. (using jQuery)

您可以像这样向输入字段添加普通事件侦听器。(使用jQuery)

$(myTextControl).change(function() {
    ...
    /* do appropriate event handling here */
    ...
});


Ok considering that the javascript which changes the input value isn't controlled by you it gets difficult. You are left with two options:

好的,考虑到更改输入值的 javascript 不是由您控制的,这会变得很困难。你有两个选择:

1.)Crossbrowser compatible: Implement polling of input value with a function which continuously checks if the value changed. (Something along these lines).

1.)跨浏览器兼容:使用连续检查输入值是否发生变化的函数来实现对输入值的轮询。(沿着这些路线的东西)。

//at beginning before other scripts changes the value create a global variable
var oldValue = myTextControl.value;

function checkIfValueChanged() {
    if(myTextControl.value != oldValue) {
        $(myTextControl).trigger("change");
        clearInterval(checker);
    }
}

//every 500ms check if value changed
var checker = setInterval('checkIfValueChanged()', 500);

Note: If your script or the user can change the value too you must implement something to catch this in order not to trigger the change event multiple times.

注意:如果您的脚本或用户也可以更改该值,您必须实施一些措施来捕获它,以免多次触发更改事件。

If the value can change multiple times by the external script just let the interval function run instead of canceling it and just update oldValue;

如果该值可以通过外部脚本多次更改,只需让间隔函数运行而不是取消它并更新 oldValue;

2.)AFAIK Not supported yet by all browsers (? test it on the ones you need to support)

2.)AFAIK 尚未被所有浏览器支持(?在您需要支持的浏览器上测试)

You could bind to a special DOM Level 3Event: DOMAttrModified(in Firefox, maybe others too I think Opera has it too, Safari??, Chrome??) and in IE of course it has a different name propertychange(and is proprietary and different from the W3C behavior)

你可以绑定到一个特殊的 DOM Level 3Event:(DOMAttrModified在 Firefox 中,也许其他人也有,我认为 Opera 也有,Safari ??,Chrome??)当然在 IE 中它有一个不同的名称propertychange(并且是专有的,与W3C 行为)

Now ideally you could combine the two options and check if support for DOMAttrModifiedor propertychangeis there and use accordingly or fallback to the polling solution.

现在理想情况下,您可以组合这两个选项并检查是否支持DOMAttrModifiedpropertychange是否存在并相应地使用或回退到轮询解决方案。



Reading links

阅读链接

W3C DOM Mutation Events

W3C DOM 突变事件

W3C DOMAttrModified Event

W3C DOMAttrModified 事件

MSDN DHTML propertychange Event

MSDN DHTML 属性更改事件

jQuery CSS Property Monitoring Plug-in updated

jQuery CSS 属性监控插件更新

Last link is some guy which basically already made a jQuery plugin doing the things described by me (untested by me, provided just as a reference)

最后一个链接是某个人基本上已经制作了一个 jQuery 插件来完成我所描述的事情(未经我测试,仅供参考)

回答by Fahim Akhtar

Use Jquery

使用jQuery

You can also use some these event listener to your input field like

您还可以将这些事件侦听器用于输入字段,例如

$("yourid").on("change",function(){
//here do something
});
$("yourid").on("keypress",function(){
//here do something
});

$("yourid").on("keydown",function(){
//here do something
});

$("yourid").on("keyup",function(){
//here do something
});

回答by ungalcrys

try this

尝试这个

$('#myTextControl').bind('input', function(){
  console.log('value changed');
});

回答by Toby

var oldVal = $('#myTextControl').val();

//Your script that changes the value

if(oldVal != $('#myTextControl').val())
{
//Your content has changed, do something
}

回答by Diodeus - James MacFarlane

You'll need to listen to keyboard events when the element you're watching has focus.

当您正在观看的元素获得焦点时,您需要监听键盘事件。