且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript - 以编程方式调用事件

更新时间:2023-11-30 16:14:34

像往常一样,你必须以一种方式为Internet Explorer做到这一点,并为其他一切做正确的方法; - )

As usual, you have to do it one way for Internet Explorer, and the correct way for everything else ;-)

对于IE:

document.getElementById("thing_with_mouseover_handler").fireEvent("onmouseover");

参见 MSDN库了解更多信息。

对于真正的浏览器:

var event = document.createEvent("MouseEvent");
event.initMouseEvent("mouseover", true, true, window);
document.getElementById("thing_with_mouseover_handler").dispatchEvent(event);

请注意,尽管第二种基于标准的方法似乎更加冗长,但它也相当多更灵活:查看文档,从 https://developer.mozilla上的Mozilla DOM事件参考开始。 org / en / DOM / event

Note that, although the second, standards-based approach seems more long-winded, it is also considerably more flexible: check the documentation, starting with the Mozilla DOM Event Reference at https://developer.mozilla.org/en/DOM/event

虽然只与您尝试做的事情有切实关系(它与自定义事件有关,而非正常事件) Dean Edwards在 http://dean.edwards.name上有一些示例代码。 / weblog / 2009/03 / callbacks-vs-events / 可能值得一看。

Although only tangentially related to what you're trying to do (it's related to custom events, rather than normal ones) Dean Edwards has some example code at http://dean.edwards.name/weblog/2009/03/callbacks-vs-events/ that may be worth a look.