javascript 触发“onchange”事件

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

Trigger "onchange" event

javascripttriggersonchange

提问by Caio

The "onchange" event is triggered only when the USER enters some value. Why isn't possible to fire the event when I change the value automatically via Javascript ? Is there an alternative ?

只有当用户输入某个值时才会触发“onchange”事件。为什么当我通过 Javascript 自动更改值时无法触发事件?有替代方案吗?

Animation:

动画片:

enter image description here

在此处输入图片说明

Code:

代码:

<!DOCTYPE html>

<html>
    <head>
        <script>
            document.addEventListener ("DOMContentLoaded", function () {
                var input = this.getElementsByTagName ("input")[0];
                var div = this.getElementsByTagName ("div")[0];
                var i = 0;
                var seconds = 5;

                div.innerHTML = "The following input should fire the event in " + seconds + " seconds";

                var interval = window.setInterval (function () {
                    i ++;

                    if (i === seconds) {
                        window.clearInterval (interval);

                        input.value = "Another example";

                        div.innerHTML = "Nothing ! Now try change the value manually";
                    }
                    else {
                        div.innerHTML = "The following input should fire the event in " + (seconds - i) + " seconds";
                    }
                }, 1000);

                input.addEventListener ("change", function () {
                    alert ("It works !");
                }, false);
            }, false);
        </script>

        <style>
            body {
                padding: 10px;
            }

            div {
                font-weight: bold;
                margin-bottom: 10px;
            }

            input {
                border: 1px solid black;
                border-radius: 3px;
                padding: 3px;
            }
        </style>

        <title>Event</title>
    </head>

    <body>
        <div></div>
        <input type = "text" value = "Example" />
    </body>
</html>

Thanks

谢谢

回答by T.J. Crowder

The vast majority of the time, you don't want an event to be fired when you change the value with code. In those cases where you do, you can fire a synthetic event on modern browsers via dispatchEvent. More here.

大多数情况下,您不希望在使用代码更改值时触发事件。在这些情况下,您可以通过dispatchEvent. 更多在这里

So in your specific example:

所以在你的具体例子中:

input.value = "Another example";
var event = document.createEvent("UIEvents"); // See update below
event.initUIEvent("change", true, true);      // See update below
input.dispatchEvent(event);

Live demo

现场演示

Update:As Benjamin noted, since the above was written, initUIEventhas been replaced with the UIEventconstructor, so that would be:

更新:正如Benjamin 所指出的,自从上述内容被写入以来,initUIEvent已被构造函数替换,因此将是:UIEvent

input.value = "Another example";
var event = new UIEvent("change", {
    "view": window,
    "bubbles": true,
    "cancelable": true
});
input.dispatchEvent(event);

Live demo

现场演示

Alternately, you can always just call whatever function you've bound to the changeevent directly, which is usually what I'd do. But sometimes you want to use actual events (for instance, when using the observer pattern) and ensure that anyone who is listening for the change is notified.

或者,您始终可以直接调用您绑定到change事件的任何函数,这通常是我要做的。但有时您想使用实际事件(例如,在使用观察者模式时)并确保任何正在侦听更改的人都得到通知。

回答by Benjamin Intal

Note that initUIEventhas been deprecated and removed from Web Standards as stated: developer.mozilla.org/en-US/docs/Web/API/UIEvent/initUIEvent

请注意,initUIEvent已弃用并从 Web 标准中删除,如下所述:developer.mozilla.org/en-US/docs/Web/API/UIEvent/initUIEvent

This is the same except that it doesn't use initUIEvent:

这是相同的,除了它不使用initUIEvent

input.value = 'Another example';
var event = new UIEvent('change', {
    'view': window,
    'bubbles': true,
    'cancelable': true
});
input.dispatchEvent(event);

回答by OnResolve

If you are changing the value progammatically, you already know when this occurs, what's to say you can't call your own method, (the same perhaps that is called from the actual trigger event handler) when you change the value?

如果您正在以编程方式更改值,那么您已经知道何时会发生这种情况,也就是说您不能在更改值时调用自己的方法(可能与从实际触发器事件处理程序调用的方法相同)?

EDIT: otherwise, if you specifically need the actual Fire to occur, you can manually dispatch the event yourself too.

编辑:否则,如果您特别需要发生实际的火灾,您也可以自己手动调度事件。

回答by Malte

The code of Crowder only gave me an TypeError (Not enough arguments to UIEvent.initUIEvent). Change it to this:

Crowder 的代码只给了我一个类型错误(UIEvent.initUIEvent 的参数不够)。改成这样:

input.value = "Another example";
var event = document.createEvent("UIEvents");
event.initUIEvent("change", true, true, window, 1);
input.dispatchEvent(event);

and it works.

它有效。