如何手动触发 onchange 事件?

我正在通过日历小部件设置日期时间文本字段值.显然,日历小部件会做这样的事情:

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;

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

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 onchange gets triggered only when the element gets focus & its value is changed on losing focus.

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

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

有什么想法吗?

推荐答案

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

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

element.onchange();

如果你需要它来完整模拟真实事件,或者如果你通过html属性或addEventListener/attachEvent设置事件,你需要做一点特征检测以正确触发事件:

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:

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

相关文章