Javascript 如何手动触发 onchange 事件?

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

How can I trigger an onchange event manually?

javascriptjavascript-eventsevent-handling

提问by CodeTweetie

I'm setting a date-time textfield value via a calendar widget. Obviously, the calendar widget does something like this :

我正在通过日历小部件设置日期时间文本字段值。显然,日历小部件执行以下操作:

document.getElementById('datetimetext').value = date_value;

What I want is : On changing value in the date-time textfield I need to reset some other fields in the page. I've added a onchange event listener to the datetimetext field which is not getting triggered, because I guess onchangegets triggered only when the element gets focus & its value is changed on losing focus.

我想要的是:在更改日期时间文本字段中的值时,我需要重置页面中的其他一些字段。我在 datetimetext 字段中添加了一个 onchange 事件侦听器,它没有被触发,因为我猜onchange只有当元素获得焦点时才会被触发,并且它的值在失去焦点时会发生变化。

Hence I'm looking for a way to manually trigger this onchangeevent (which I guess should take care of checking the value difference in the text field).

因此,我正在寻找一种手动触发此onchange事件的方法(我想这应该负责检查文本字段中的值差异)。

Any ideas ?

有任何想法吗 ?

回答by Andy E

There's a couple of ways you can do this. If the onchangelistener is a function set via the element.onchangeproperty and you're not bothered about the event object or bubbling/propagation, the easiest method is to just call that function:

有几种方法可以做到这一点。如果onchange侦听器是通过element.onchange属性设置的函数,并且您不关心事件对象或冒泡/传播,则最简单的方法是调用该函数:

element.onchange();

If you need it to simulate the real event in full, or if you set the event via the html attribute or addEventListener/attachEvent, you need to do a bit of feature detection to correctly fire the event:

如果您需要它来完全模拟真实事件,或者如果您通过 html 属性或addEventListener/设置事件attachEvent,则需要进行一些功能检测以正确触发事件:

if ("createEvent" in document) {
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("change", false, true);
    element.dispatchEvent(evt);
}
else
    element.fireEvent("onchange");

回答by Milan Iliev

MDNsuggests that there's a much cleaner way of doing this in modern browsers:

MDN建议在现代浏览器中有一种更简洁的方法来做到这一点:

// Assuming we're listening for e.g. a 'change' event on `element`

// Create a new 'change' event
var event = new Event('change');

// Dispatch it.
element.dispatchEvent(event);

回答by Jacob Mouka

For those using jQuery there's a convenient method: http://api.jquery.com/change/

对于那些使用 jQuery 的人,有一个方便的方法:http: //api.jquery.com/change/