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:(如果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");
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…