javascript 一种附加事件监听器的方法,所有主流浏览器都支持

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11521160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:30:08  来源:igfitidea点击:

A method of attaching event listener, supported by all major web browsers

javascriptjqueryinternet-explorerjavascript-events

提问by trejder

I need to write a piece of code that will attach a listener to selected event, and that will work in any popular browser, in any version of it. After doing some searching I came out with following function:

我需要编写一段代码,将侦听器附加到所选事件,并且可以在任何流行浏览器的任何版本中使用。做了一些搜索后,我得出了以下功能:

function addListener(event, thefunction)
{
    if(window.addEventListener)
    {
        //All browsers, except IE before version 9.
        window.addEventListener(event, thefunction, false);
    } 
    else if(window.attachEvent)
    {
        //IE before version 9.
        window.attachEvent(event, thefunction);
    }
}

Quite simple and seems to be self-explanatory.

很简单,似乎不言自明。

There might be some problem with DOMContentLoadedevent, as none version of IE (AFAIK) does recognizes it, and developers are obligated to use onreadystatechangeinstead. Solving this problem also seems to be fairly simple, until Internet Explorer 9. You had to write only an extra line in else if(window.attachEvent):

DOMContentLoaded事件可能存在一些问题,因为没有任何版本的 IE (AFAIK) 识别它,开发人员有义务使用它onreadystatechange。解决这个问题似乎也相当简单,直到 Internet Explorer 9。您只需要在 中多写一行else if(window.attachEvent)

event = (event == 'DOMContentLoaded') ? 'onreadystatechange' : "on" + event;

This part was always fired in any version of Internet Explorer and this line provided a simple translation of event name, so a correct one was always used.

这部分总是在任何版本的 Internet Explorer 中触发,这一行提供了事件名称的简单翻译,因此总是使用正确的。

But what about Internet Explorer 9 (and above)? In which Microsoft decided that it will drop attachEventin favor of addEventListener. But doesn't changed onreadystatechangeinto DOMContentLoaded.

但是 Internet Explorer 9(及更高版本)呢?其中微软决定将放弃attachEvent支持addEventListener. 但不会onreadystatechange变成DOMContentLoaded.

I can't use above line in window.addEventListenerpart, because this will rewrite DOMContentLoadedinto onreadystatechangeevent even for other browsers and fail there, as they use DOMContentLoaded.

我不能window.addEventListener部分使用上面的行,因为即使对于其他浏览器,这也会重写DOMContentLoadedonreadystatechange事件并在那里失败,因为他们使用DOMContentLoaded.

So, does the only way to solve this problem, is to add browser detection (type and version) to window.addEventListenerpart and if it detects that script is dealing with IE 9 or above, it will rewrite event name from DOMContentLoadedto onreadystatechange(and supplement other events name with on, required for IE), and in case of other browsers, will leave event name not changed?

那么,解决这个问题的唯一办法,就是在window.addEventListenerpart中加入浏览器检测(类型和版本),如果检测到脚本是在处理IE 9或更高版本,则将事件名称从DOMContentLoadedto重写onreadystatechange(并补充其他事件名称) with on, IE 需要),如果是其他浏览器,会不会保留事件名称不变?

Or maybe I'm wrong, because as I just tested, neither DOMContentLoadednor onreadystatechangeis being fired in my IE 8 (first one fires correctly in FF / Chrome).

或者也许我错了,因为正如我刚刚测试的那样,在我的 IE 8 中既没有DOMContentLoaded也没有onreadystatechange被触发(第一个在 FF / Chrome 中正确触发)。

And what about jQuery's .on()function (or similar)? Does anyone knows, if it supports cross-browser attaching of DOMContentLoaded, so I can be sure that this specific kind of event will be catch by my script, no matter, in which browser or it's version I'm using?

那么 jQuery 的.on()功能(或类似功能)呢?有谁知道,如果它支持DOMContentLoaded.

采纳答案by Fabrício Matté

DOMContentLoadedis natively supported in IE9 and above and can be attached through the W3C-standard addEventListenermethod which was also implemented in IE9:

DOMContentLoaded在 IE9 及更高版本中原生支持,可以通过 W3C 标准addEventListener方法附加,该方法也在 IE9 中实现:

document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM ready');
}, false);

That will work in all modern browsers and IE from version 9 and up.

这将适用于版本 9 及更高版本的所有现代浏览器和 IE。

jQuery 1.x is compatible with IE6+ and any other update-to-date browser. jQuery can hook a DOM ready event cross-browser by shimming support for IE6-8 through the DOM ready handler:

jQuery 1.x 与 IE6+ 和任何其他更新到最新的浏览器兼容。jQuery 可以通过DOM 就绪处理程序通过填充对 IE6-8 的支持来跨浏览器挂钩 DOM 就绪事件:

$(function() {
    //DOM has loaded, put your code here
});


.on()provides event delegation, but that's rather unrelated to the question.

.on()提供事件委托,但这与问题无关。

回答by Utkanos

IE9 supports DOMContentLoaded. See here.

IE9 支持 DOMContentLoaded。见这里

With this in mind, you can pretty much* work on the assumption that, if addEventListeneris supported, so is DOMContentLoaded.

考虑到这一点,您几乎可以假设addEventListenerDOMContentLoaded如果受支持,则它也可以工作。

(* unless someone lands on your page using Opera 8 or Safari 3.0, probably unlikely).

(* 除非有人使用 Opera 8 或 Safari 3.0 登陆您的页面,可能不太可能)。

As for jQuery, it defers to DOMContentLoaded where this is supported but otherwise falls back to its historic means of detecting DOM-ready, which involves repeatedly checking the DOM tree to see if document.bodyexists yet. So you can just use its DOM-ready handler:

至于 jQuery,它在支持 DOMContentLoaded 的情况下使用它,但在其他方面则退回到其检测 DOM-ready 的历史方法,这涉及重复检查 DOM 树以查看是否document.body存在。所以你可以使用它的 DOM-ready 处理程序:

$(function() {

without having to use on().

无需使用on().

More info on how jQuery does it in this answer.

在此答案中有关 jQuery 如何做到这一点的更多信息。