在IE javascript中添加eventListener [英] Add eventListener in IE javascript

查看:61
本文介绍了在IE javascript中添加eventListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码适用于Chrome,但不适用于Internet Explorer 8/9。

This code works nicely in for example Chrome, but not in Internet Explorer 8/9.

/* sitepoint.com/javascript-this-event-handlers */
function AttachEvent(element, type, handler){if (element.addEventListener){element.addEventListener(type, handler, false);}else{element.attachEvent("on"+type, handler);}}

window.addEventListener("load", function() {

            //do some stuff

            AttachEvent(id, "click", function_name); 

}, false);

IE已经抱怨addEventListener行。
我相信我需要使用attachEvent。我该怎么做呢?我宁愿保留在其他浏览器中工作的代码,只在Internet Explorer中使用attachEvent。
如何使这种跨浏览器兼容?

IE already complains about the addEventListener line. I believe I need to use attachEvent instead. How do I do this? I would prefer to keep the code that is working in the other browsers and only use attachEvent in Internet Explorer. How do I get this cross-browser compatible?

推荐答案

IE9 支持 addEventListener()

以下是现有函数与 attachEvent (以及* 属性中的旧)。

Here is how your existing function would work with attachEvent (and the old on* property).

// logic to attach the event correctly in IE9
function AttachEvent(element, type, handler) {
    if (element.addEventListener) {
        element.addEventListener(type, handler, false);
    }else if (element.attachEvent) {
        element.attachEvent('on' + type, handler)
    } else {
        element['on' + type] = handler;
    }
}

然后设置窗口加载事件.. 。

You'd then set the window load event...

AttachEvent(window, "load", function() {
    // ...
});     

不要忘记事件是与较旧的IE一起全球化。如果你愿意,你可以编写脚本。你只需让每个函数调用这个 callback(),它将继续调用用户提供的 handler()用正确的论点。

Don't forget that the event is global with the older IEs. You could script around that if you wanted to. You'd simply have each function call this callback() which would go on to invoke the user-supplied handler() with the correct arguments.

var callback = function(e) {
    e = e || window.event;
    handler.call(element, e);
};

你可能会被带走并尝试规范化事件的属性,例如 target / srcElement ,但是你可能想要考虑一个现有的库。

You could get carried away and try and normalise properties on event, such as target/srcElement, but then you might want to consider an existing library.

这篇关于在IE javascript中添加eventListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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