javascript Javascript添加事件跨浏览器功能实现:使用attachEvent/addEventListener vs inline events

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3763080/
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-25 02:10:21  来源:igfitidea点击:

Javascript add events cross-browser function implementation: use attachEvent/addEventListener vs inline events

javascripteventsjavascript-eventsevent-handling

提问by Marco Demaio

In order to add events we could use this simple 1st solution:

为了添加事件,我们可以使用这个简单的第一个解决方案

function AddEvent(html_element, event_name, event_function) 
{       
   if(html_element.attachEvent) //Internet Explorer
      html_element.attachEvent("on" + event_name, function() {event_function.call(html_element);}); 
   else if(html_element.addEventListener) //Firefox & company
      html_element.addEventListener(event_name, event_function, false); //don't need the 'call' trick because in FF everything already works in the right way          
} 

or this 2nd solution(that adds inline events):

第二个解决方案(添加内联事件):

function AddEvent(html_element, event_name, event_function) 
{       
   var old_event = html_element['on' + event_name];
   if(typeof old_event !== 'function')
      html_element['on' + event_name] = function() { event_function.call(html_element); };
   else
      html_element['on' + event_name] = function() { old_event(); event_function.call(html_element); };
}

These are both cross-browsersand can be used in this way:

这些都是跨浏览器,可以这样使用:

AddEvent(document.getElementById('some_div_id'), 'click', function() 
{             
   alert(this.tagName); //shows 'DIV'
});  

Since I have the feeling attachEvent/addEventListenerare used more around in events handling implementations, I'm wondering:

由于我感觉attachEvent/addEventListener在事件处理实现中使用得更多,我想知道:

Are there any disadvantages/drawbacks against using the 2nd solution that I might better be aware of?

使用我可能更清楚的第二个解决方案是否有任何缺点/缺点?

I can see two, but I'm interested in more (if any):

我可以看到两个,但我对更多(如果有)感兴趣:

  1. the 2nd solution screws up innerHTML of elements by adding events inline
  2. Using 2nd solution I can easily remove all functions associated with a certain event type (html_element['on' + event_name] = null), but I can not use detachEvent/removeEventListenerto remove exactly a specific function.
  1. 第二个解决方案通过添加内联事件来破坏元素的innerHTML
  2. 使用第二个解决方案,我可以轻松删除与特定事件类型 ( html_element['on' + event_name] = null)关联的所有函数,但我不能detachEvent/removeEventListener用来完全删除特定函数。

Any answers like: "use jQuery" or any other FW are pointless!

任何诸如“使用 jQuery”或任何其他 FW 之类的答案都是毫无意义的!

采纳答案by yorick

With the 2nd solution, you have to manually call the previous functions, making it hard to remove specific listeners (which, to me, sounds like something you'd rather want than clearing all listeners), while on the first solution, you can only clear them all at the same time, unless you want to emulate the first functionality.

使用第二个解决方案,您必须手动调用之前的函数,从而很难删除特定的侦听器(对我来说,这听起来像是您宁愿想要而不是清除所有侦听器的东西),而在第一个解决方案中,您只能同时清除它们,除非您想模拟第一个功能。

Personally, I always use the first solution, because it has the advantage of not having to worry about clearing possible other event listeners.

就我个人而言,我总是使用第一种解决方案,因为它的优点是不必担心清除可能的其他事件侦听器。

The mozilla wikialso lists the advantages that the first solution works on any DOM element, not just HTML elements, and that it allows finer grained control over the phase when the listener gets activated (capturing vs. bubbling) with the third argument.

Mozilla的维基还列出了第一个解决方案工作于任何DOM元素,而不仅仅是HTML元素上的优势,而且它允许细粒度的控制时,听众被激活的阶段(捕获与冒泡)与第三个参数。

回答by Fareed Alnamrouti

i would use both codes like this

我会像这样使用这两个代码

function addEvent(html_element, event_name, event_function) {
    if (html_element.addEventListener) { // Modern
        html_element.addEventListener(event_name, event_function, false);
    } else if (html_element.attachEvent) { // Internet Explorer
        html_element.attachEvent("on" + event_name, event_function);
    } else { // others
        html_element["on" + event_name] = event_function;
    }
};