Javascript - 以编程方式调用事件 [英] Javascript - programmatically invoking events

查看:172
本文介绍了Javascript - 以编程方式调用事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我使用addEventListener或attachEvent(取决于浏览器)向对象添加事件;是否有可能以后以编程方式调用这些事件?

Say I add events to an object using either addEventListener or attachEvent (depending on the browser); is it possible to later invoke those events programmatically?

使用如下对象添加/删除事件处理程序:

The events handlers are added/removed using an object like this:

var Event = {
    add: function(obj,type,fn) {
        if (obj.attachEvent) {
            obj.attachEvent('on'+type,fn);
        } else {
            obj.addEventListener(type,fn,false);
        }
    },
    remove: function(obj,type,fn) {
        if (obj.detachEvent) {
            obj.detachEvent('on'+type,fn);
        } else {
            obj.removeEventListener(type,fn,false);
        }
    }
}

或者我是否需要存储每个处理程序的副本,只需添加一个Event.invoke(...)函数?

Or do I need to store copies of each handler and just add an Event.invoke(...) function?

编辑:此外,jQuery不是一个选项:D

Also, jQuery is not an option :D

推荐答案

像往常一样,你必须以一种方式为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.

这篇关于Javascript - 以编程方式调用事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆