addEventListener vs onclick [英] addEventListener vs onclick

查看:116
本文介绍了addEventListener vs onclick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

addEventListener onclick 之间的区别是什么?

What's the difference between addEventListener and onclick?

var h = document.getElementById("a");
h.onclick = dothing1;
h.addEventListener("click", dothing2);

上面的代码一起存放在一个单独的.js文件中,它们都能很好地工作。

The code above resides together in a separate .js file, and they both work perfectly.

推荐答案

两者都是正确的,但它们本身都不是最佳,开发人员可能选择使用这两种方法。

Both are correct, but none of them are "best" per se, and there may be a reason the developer chose to use both approaches.

事件监听器(addEventListener和IE的attachEvent)

Internet的早期版本资源管理器实现javascript与几乎所有其他浏览器不同。对于小于9的版本,您使用 attachEvent [ doc ]方法,如下所示:

Earlier versions of Internet Explorer implement javascript differently from pretty much every other browser. With versions less than 9, you use the attachEvent[doc] method, like this:

element.attachEvent('onclick', function() { /* do stuff here*/ });

在大多数其他浏览器(包括IE 9及更高版本)中,您使用 addEventListener [ doc ],像这样:

In most other browsers (including IE 9 and above), you use addEventListener[doc], like this:

element.addEventListener('click', function() { /* do stuff here*/ }, false);

使用这种方法( DOM Level 2事件),您可以将理论上无限数量的事件附加到任何单个元素。唯一的实际限制是客户端内存和其他性能问题,每个浏览器都有所不同。

Using this approach (DOM Level 2 events), you can attach a theoretically unlimited number of events to any single element. The only practical limitation is client-side memory and other performance concerns, which are different for each browser.

上面的示例表示使用匿名函数[ doc ]。您还可以使用函数引用添加事件侦听器[ doc ]或关闭[ doc ]:

The examples above represent using an anonymous function[doc]. You can also add an event listener using a function reference[doc] or a closure[doc]:

var myFunctionReference = function() { /* do stuff here*/ }

element.attachEvent('onclick', myFunctionReference);
element.addEventListener('click', myFunctionReference , false);

addEventListener 的另一个重要特征是最终参数,控制侦听器对冒泡事件的反应[ doc ]。我在示例中传递了错误,这可能是95%的用例的标准。 attachEvent 或使用内联事件时没有等效参数。

Another important feature of addEventListener is the final parameter, which controls how the listener reacts to bubbling events[doc]. I've been passing false in the examples, which is standard for probably 95% of use cases. There is no equivalent argument for attachEvent, or when using inline events.

内联事件(HTML onclick =property和element.onclick)

在所有支持javascript的浏览器中,您可以将事件侦听器内联,即HTML代码中的内容。你可能已经看过了:

In all browsers that support javascript, you can put an event listener inline, meaning right in the HTML code. You've probably seen this:

<a id="testing" href="#" onclick="alert('did stuff inline');">Click me</a>

大多数有经验的开发人员避开这种方法,但它确实完成了工作;它简单直接。你可能不会在这里使用闭包或匿名函数(虽然处理程序本身是各种类型的匿名函数),并且你对范围的控制是有限的。

Most experienced developers shun this method, but it does get the job done; it is simple and direct. You may not use closures or anonymous functions here (though the handler itself is an anonymous function of sorts), and your control of scope is limited.

你提到的另一种方法:

element.onclick = function () { /*do stuff here */ };

...相当于内联javascript,除了你有更多的范围控制权(因为你'编写脚本而不是HTML)并且可以使用匿名函数,函数引用和/或闭包。

... is the equivalent of inline javascript except that you have more control of the scope (since you're writing a script rather than HTML) and can use anonymous functions, function references, and/or closures.

内联事件的一个重要缺点是与描述的事件监听器不同在上面,您可能只分配了一个内联事件。内联事件存储为元素的属性/属性[ doc ],意思是它可以被覆盖。

The significant drawback with inline events is that unlike event listeners described above, you may only have one inline event assigned. Inline events are stored as an attribute/property of the element[doc], meaning that it can be overwritten.

使用上面HTML中的示例< a>

Using the example <a> from the HTML above:

var element = document.getElementById('testing');
element.onclick = function () { alert('did stuff #1'); };
element.onclick = function () { alert('did stuff #2'); };

...当你点击元素时,你只 看到问题#2 - 你用第二个值覆盖了 onclick 属性的第一个分配,并覆盖原始内联HTML onclick 属性也是。请在此处查看: http://jsfiddle.net/jpgah/

... when you clicked the element, you'd only see "Did stuff #2" - you overwrote the first assigned of the onclick property with the second value, and you overwrote the original inline HTML onclick property too. Check it out here: http://jsfiddle.net/jpgah/.

哪个最好?

问题在于浏览器的兼容性和必要性。您当前是否需要将多个事件附加到元素?你将来会吗?赔率是,你会的。 attachEvent和addEventListener是必要的。如果没有,内联事件将起作用。

The question is a matter of browser compatibility and necessity. Do you currently need to attach more than one event to an element? Will you in the future? Odds are, you will. attachEvent and addEventListener are necessary. If not, an inline event will do the trick.

jQuery和其他javascript框架在通用模型中封装了DOM 2级事件的不同浏览器实现,因此您可以编写交叉符合浏览器的代码,无需担心IE作为反叛者的历史。与jQuery相同的代码,所有跨浏览器并准备摇滚:

jQuery and other javascript frameworks encapsulate the different browser implementations of DOM level 2 events in generic models so you can write cross-browser compliant code without having to worry about IE's history as a rebel. Same code with jQuery, all cross-browser and ready to rock:

$(element).on('click', function () { /* do stuff */ });

不过,为了这一件事,不要用完并获得一个框架。您可以轻松地滚动自己的小工具来处理旧浏览器:

Don't run out and get a framework just for this one thing, though. You can easily roll your own little utility to take care of the older browsers:

function addEvent(element, evnt, funct){
  if (element.attachEvent)
   return element.attachEvent('on'+evnt, funct);
  else
   return element.addEventListener(evnt, funct, false);
}

// example
addEvent(
    document.getElementById('myElement'),
    'click',
    function () { alert('hi!'); }
);

试试看: http://jsfiddle.net/bmArj/

考虑到所有这一切,除非您正在查看的脚本采取了浏览器差异考虑在某种其他方式(代码未在您的问题中显示),使用 addEventListener 的部分在小于9的IE版本中不起作用。

Taking all of that into consideration, unless the script you're looking at took the browser differences into account some other way (in code not shown in your question), the part using addEventListener would not work in IE versions less than 9.

文档和相关阅读

  • W3 HTML specification, element Event Handler Attributes
  • element.addEventListener on MDN
  • element.attachEvent on MSDN
  • Jquery.on
  • quirksmode blog "Introduction to Events"
  • CDN-hosted javascript libraries at Google

这篇关于addEventListener vs onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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