Javascript addEventListener 与 onclick

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

addEventListener vs onclick

javascriptonclickaddeventlistener

提问by William Sham

What's the difference between addEventListenerand onclick?

addEventListener和 和有onclick什么区别?

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

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

上面的代码一起存在于一个单独的 .js 文件中,它们都可以完美地工作。

回答by Chris Baker

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

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

Event Listeners (addEventListener and IE's attachEvent)

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

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:

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

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

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

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

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

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.

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

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]:

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

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

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

Another important feature of addEventListeneris 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.

的另一个重要特性addEventListener是 final 参数,它控制侦听器如何对冒泡事件做出反应[ doc]。我一直在示例中传递 false,这对于大约 95% 的用例来说是标准的。attachEvent, 或使用内联事件时没有等效的参数。

Inline events (HTML onclick="" property and element.onclick)

内联事件(HTML onclick="" 属性和 element.onclick)

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

在所有支持 javascript 的浏览器中,您可以将事件侦听器内联,这意味着就在 HTML 代码中。你可能见过这个:

<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.

大多数有经验的开发人员都避免使用这种方法,但它确实可以完成工作;它简单而直接。您不能在这里使用闭包或匿名函数(尽管处理程序本身是某种匿名函数),并且您对范围的控制是有限的。

The other method you mention:

你提到的另一种方法:

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

... 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.

... 相当于内联 javascript,除了您可以更好地控制范围(因为您正在编写脚本而不是 HTML)并且可以使用匿名函数、函数引用和/或闭包。

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.

内联事件的显着缺点是与上述事件侦听器不同,您可能只分配了一个内联事件。内联事件存储为元素 [ doc]的属性/属性,这意味着它可以被覆盖。

Using the example <a>from the HTML above:

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

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

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

...当您单击该元素时,您只会看到“Did stuff #2” - 您onclick用第二个值覆盖了该属性的第一个分配,并且您也覆盖了原始的内联 HTMLonclick属性。在这里查看:http: //jsfiddle.net/jpgah/

Broadly speaking, do not use inline events. There may be specific use cases for it, but if you are not 100% sure you have that use case, then you do not and should not use inline events.

从广义上讲,不要使用内联事件。它可能有特定的用例,但如果您不是 100% 确定您有该用例,那么您不会也不应该使用内联事件。

Modern Javascript (Angular and the like)

现代 Javascript(Angular 等)

Since this answer was originally posted, javascript frameworks like Angular have become far more popular. You will see code like this in an Angular template:

自从这个答案最初发布以来,像 Angular 这样的 javascript 框架变得越来越流行。您将在 Angular 模板中看到这样的代码:

<button (click)="doSomething()">Do Something</button>

This looks like an inline event, but it isn't. This type of template will be transpiled into more complex code which uses event listeners behind the scenes. Everything I've written about events here still applies, but you are removed from the nitty gritty by at least one layer. You should understand the nuts and bolts, but if your modern JS framework best practices involve writing this kind of code in a template, don't feel like you're using an inline event -- you aren't.

这看起来像一个内联事件,但事实并非如此。这种类型的模板将被转译为在幕后使用事件侦听器的更复杂的代码。我在这里写的关于事件的所有内容仍然适用,但至少你已经从本质上移除了一层。您应该了解具体细节,但如果您的现代 JS 框架最佳实践涉及在模板中编写此类代码,请不要觉得您在使用内联事件——您不是。

Which is Best?

哪个最好?

The question is a matter of browser compatibility and necessity. Do you 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 may seem like they'd do the trick, but you're much better served preparing for a future that, though it may seem unlikely, is predictable at least. There is a chance you'll have to move to JS-based event listeners, so you may as well just start there. Don't use inline events.

问题是浏览器兼容性和必要性的问题。您是否需要将多个事件附加到一个元素?你将来会吗?很有可能,你会的。attachEvent 和 addEventListener 是必需的。如果没有,内联事件似乎可以解决问题,但您最好为未来做好准备,尽管这似乎不太可能,但至少是可以预测的。您有可能不得不转向基于 JS 的事件侦听器,因此您不妨从那里开始。不要使用内联事件。

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:

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

$(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!'); }
);

Try it: http://jsfiddle.net/bmArj/

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

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 addEventListenerwould not work in IE versions less than 9.

考虑到所有这些,除非您正在查看的脚本以其他方式考虑了浏览器的差异(在您的问题中未显示的代码中),addEventListener否则使用的部分将无法在低于 9 的 IE 版本中使用。

Documentation and Related Reading

文档和相关阅读

回答by lonesomeday

The difference you could see if you had another couple of functions:

如果您有另外几个功能,您可以看到不同之处:

var h = document.getElementById('a');
h.onclick = doThing_1;
h.onclick = doThing_2;

h.addEventListener('click', doThing_3);
h.addEventListener('click', doThing_4);

Functions 2, 3 and 4 work, but 1 does not. This is because addEventListenerdoes not overwrite existing event handlers, whereas onclickoverrides any existing onclick = fnevent handlers.

功能 2、3 和 4 有效,但 1 无效。这是因为addEventListener不会覆盖现有的事件处理程序,而是onclick覆盖任何现有的onclick = fn事件处理程序。

The other significant difference, of course, is that onclickwill always work, whereas addEventListenerdoes not work in Internet Explorer before version 9. You can use the analogous attachEvent(which has slightlydifferent syntax) in IE <9.

当然,另一个显着区别是它onclick始终有效,而addEventListener在版本 9 之前的 Internet Explorer 中不起作用。您可以在 IE <9 中使用类似的attachEvent(语法略有不同)。

回答by Micha? Per?akowski

In this answer I will describe the three methods of defining DOM event handlers.

在这个答案中,我将描述定义 DOM 事件处理程序的三种方法。

element.addEventListener()

element.addEventListener()

Code example:

代码示例:

const element = document.querySelector('a');
element.addEventListener('click', event => event.preventDefault(), true);
<a href="//google.com">Try clicking this link.</a>

element.addEventListener()has multiple advantages:

element.addEventListener()具有多重优势:

  • Allows you to register unlimitedevents handlers and remove them with element.removeEventListener().
  • Has useCaptureparameter, which indicates whether you'd like to handle event in its capturing or bubbling phase. See: Unable to understand useCapture attribute in addEventListener.
  • Cares about semantics. Basically, it makes registering event handlers more explicit. For a beginner, a function call makes it obvious that something happens, whereas assigning event to some property of DOM element is at least not intuitive.
  • Allows you to separate document structure (HTML) and logic (JavaScript). In tiny web applications it may not seem to matter, but it doesmatter with any bigger project. It's way much easier to maintain a project which separates structure and logic than a project which doesn't.
  • Eliminates confusion with correct event names. Due to using inline event listeners or assigning event listeners to .oneventproperties of DOM elements, lots of inexperienced JavaScript programmers thinks that the event name is for example onclickor onload. onis nota part of event name. Correct event names are clickand load, and that's how event names are passed to .addEventListener().
  • Works in almost all browser. If you still have to support IE <= 8, you can use a polyfill from MDN.
  • 允许您注册无限的事件处理程序并使用element.removeEventListener().
  • useCapture参数,它指示你是想在它的捕获阶段还是冒泡阶段处理事件。请参阅:无法理解 addEventListener 中的 useCapture 属性
  • 关心语义。基本上,它使注册事件处理程序更加明确。对于初学者来说,函数调用很明显发生某些事情,而将事件分配给 DOM 元素的某些属性至少不直观。
  • 允许您分离文档结构 (HTML) 和逻辑 (JavaScript)。在小型 Web 应用程序中,这似乎无关紧要,但对于任何更大的项目来说,它确实很重要。维护一个分离结构和逻辑的项目比一个不分离的项目容易得多。
  • 消除与正确事件名称的混淆。由于使用内联事件侦听器或将事件侦听器分配给.oneventDOM 元素的属性,许多没有经验的 JavaScript 程序员认为事件名称是例如onclickonloadon不是事件名称的一部分。正确的事件名称是clickand load,这就是事件名称传递给 的方式.addEventListener()
  • 适用于几乎所有浏览器。如果您仍然必须支持 IE <= 8,则可以使用MDN 中的 polyfill

element.onevent = function() {}(e.g. onclick, onload)

element.onevent = function() {}(例如onclick, onload)

Code example:

代码示例:

const element = document.querySelector('a');
element.onclick = event => event.preventDefault();
<a href="//google.com">Try clicking this link.</a>

This was a way to register event handlers in DOM 0. It's now discouraged, because it:

这是一种在 DOM 0 中注册事件处理程序的方法。现在不鼓励这样做,因为它:

  • Allows you to register only oneevent handler. Also removing the assigned handler is not intuitive, because to remove event handler assigned using this method, you have to revert oneventproperty back to its initial state (i.e. null).
  • Doesn't respond to errorsappropriately. For example, if you by mistake assign a string to window.onload, for example: window.onload = "test";, it won't throw any errors. Your code wouldn't work and it would be really hard to find out why. .addEventListener()however, would throw error (at least in Firefox): TypeError: Argument 2 of EventTarget.addEventListener is not an object.
  • Doesn't provide a way to choose if you want to handle event in its capturing or bubbling phase.
  • 允许您注册一个事件处理程序。删除分配的处理程序也不直观,因为要删除使用此方法分配的事件处理程序,您必须将onevent属性恢复到其初始状态(即null)。
  • 不对错误做出适当的响应。例如,如果您错误地将字符串分配给window.onload,例如: window.onload = "test";,它不会抛出任何错误。您的代码不起作用,而且很难找出原因。.addEventListener()但是,会抛出错误(至少在 Firefox 中):TypeError: Argument 2 of EventTarget.addEventListener is not an object
  • 不提供选择是否要在其捕获或冒泡阶段处理事件的方法。

Inline event handlers (oneventHTML attribute)

内联事件处理程序(oneventHTML 属性)

Code example:

代码示例:

<a href="//google.com" onclick="event.preventDefault();">Try clicking this link.</a>

Similarly to element.onevent, it's now discouraged. Besides the issues that element.oneventhas, it:

与 类似element.onevent,现在不鼓励使用。除了存在的问题外element.onevent,它还:

  • Is a potential security issue, because it makes XSS much more harmful. Nowadays websites should send proper Content-Security-PolicyHTTP header to block inline scripts and allow external scripts only from trusted domains. See How does Content Security Policy work?
  • Doesn't separate document structure and logic.
  • If you generate your page with a server-side script, and for example you generate a hundred links, each with the same inline event handler, your code would be much longer than if the event handler was defined only once. That means the client would have to download more content, and in result your website would be slower.
  • 是一个潜在的安全问题,因为它使 XSS 危害更大。现在网站应该发送正确的Content-Security-PolicyHTTP 标头来阻止内联脚本,并只允许来自受信任域的外部脚本。请参阅内容安全策略如何工作?
  • 分离文档结构和逻辑
  • 如果您使用服务器端脚本生成页面,例如生成一百个链接,每个链接都具有相同的内联事件处理程序,则您的代码将比事件处理程序仅定义一次时长得多。这意味着客户端将不得不下载更多内容,结果您的网站会变慢。

See also

也可以看看

回答by Magnar

While onclickworks in all browsers, addEventListenerdoes not work in older versions of Internet Explorer, which uses attachEventinstead.

虽然onclick适用于所有浏览器,addEventListener但不适用于旧版本的 Internet Explorer,而是使用attachEvent

The downside of onclickis that there can only be one event handler, while the other two will fire all registered callbacks.

缺点onclick是只能有一个事件处理程序,而另外两个将触发所有已注册的回调。

回答by jAndy

As far as I know, the DOM "load" event still does only work very limited. That means it'll only fire for the window object, imagesand <script>elements for instance. The same goes for the direct onloadassignment. There is no technical difference between those two. Probably .onload =has a better cross-browser availabilty.

据我所知,DOM“加载”事件的作用仍然非常有限。这意味着它只会为window object,images<script>元素触发。直接onload赋值也是如此。这两者之间没有技术差异。可能.onload =有更好的跨浏览器可用性。

However, you cannot assign a load eventto a <div>or <span>element or whatnot.

但是,您不能将 a 分配load event给 a<div><span>元素或诸如此类的东西。

回答by Willem van der Veen

Summary:

概括:

  1. addEventListenercan add multiple events, whereas with onclickthis cannot be done.
  2. onclickcan be added as an HTMLattribute, whereas an addEventListenercan only be added within <script>elements.
  3. addEventListenercan take a third argument which can stop the event propagation.
  1. addEventListener可以添加多个事件,而onclick不能这样做。
  2. onclick可以作为HTML属性添加,而 anaddEventListener只能添加在<script>元素中。
  3. addEventListener可以采用可以停止事件传播的第三个参数。

Both can be used to handle events. However, addEventListenershould be the preferred choice since it can do everything onclickdoes and more. Don't use inline onclickas HTML attributes as this mixes up the javascript and the HTML which is a bad practice. It makes the code less maintainable.

两者都可用于处理事件。但是,addEventListener应该是首选,因为它可以做任何事情onclick,甚至更多。不要将内联onclick用作 HTML 属性,因为这会混淆 javascript 和 HTML,这是一种不好的做法。它使代码的可维护性降低。

回答by a guest

One detail hasn't been noted yet: modern desktop browsers consider different button presses to be "clicks" for AddEventListener('click'and onclickby default.

有一个细节没有注意到尚:现代桌面浏览器考虑不同的按键操作是“点击”了AddEventListener('click',并onclick在默认情况下。

  • On Chrome 42 and IE11, both onclickand AddEventListenerclick fire on left and middle click.
  • On Firefox 38, onclickfires onlyon left click, but AddEventListenerclick fires on left, middle andright clicks.
  • 在Chrome 42和IE11,双方onclickAddEventListener单击火左边和中间点击。
  • 在Firefox 38,onclick触发在左侧点击,但AddEventListener点击左,中火右点击。

Also, middle-click behavior is veryinconsistent across browsers when scroll cursors are involved:

此外,当涉及滚动光标时,跨浏览器的中键行为非常不一致:

  • On Firefox, middle-click events always fire.
  • On Chrome, they won't fire if the middleclick opens or closes a scroll cursor.
  • On IE, they fire when scroll cursor closes, but not when it opens.
  • 在 Firefox 上,鼠标中键事件总是会触发。
  • 在 Chrome 上,如果鼠标中键打开或关闭滚动光标,它们将不会触发。
  • 在 IE 上,它们会在滚动光标关闭时触发,但不会在打开时触发。

It is also worth noting that "click" events for any keyboard-selectable HTML element such as inputalso fire on space or enter when the element is selected.

还值得注意的是,任何可用键盘选择的 HTML 元素的“单击”事件,例如input也会在空格上触发或在元素被选择时输入。

回答by jgmjgm

Javascript tends to blend everything into objects and that can make it confusing. All into one is the JavaScript way.

Javascript 倾向于将所有内容混合到对象中,这可能会让人感到困惑。合二为一就是 JavaScript 的方式。

Essentially onclick is a HTML attribute. Conversely addEventListener is a method on the DOM object representing a HTML element.

本质上 onclick 是一个 HTML 属性。相反,addEventListener 是表示 HTML 元素的 DOM 对象上的方法。

In JavaScript objects, a method is merely a property that has a function as a value and that works against the object it is attached to (using this for example).

在 JavaScript 对象中,方法只是一个属性,它具有一个函数作为值,并且可以对它所附加的对象起作用(例如使用 this)。

In JavaScript as HTML element represented by DOM will have it's attributes mapped onto its properties.

在 JavaScript 中,由 DOM 表示的 HTML 元素会将其属性映射到其属性上。

This is where people get confused because JavaScript melds everything into a single container or namespace with no layer of indirection.

这就是人们感到困惑的地方,因为 JavaScript 将所有内容都融合到一个没有间接层的容器或命名空间中。

In a normal OO layout (which does at least merge the namespace of properties/methods) you would might have something like:

在普通的 OO 布局中(它至少合并了属性/方法的命名空间),你可能会有类似的东西:

domElement.addEventListener // Object(Method)
domElement.attributes.onload // Object(Property(Object(Property(String))))

There are variations like it could use a getter/setter for onload or HashMap for attributes but ultimately that's how it would look. JavaScript eliminated that layer of indirection at the expect of knowing what's what among other things. It merged domElement and attributes together.

有一些变体,比如它可以使用 getter/setter 进行加载或使用 HashMap 进行属性,但最终这就是它的外观。JavaScript 消除了间接层,期望知道什么是什么等等。它将 domElement 和属性合并在一起。

Barring compatibility you should as a best practice use addEventListener. As other answers talk about the differences in that regard rather than the fundamental programmatic differences I will forgo it. Essentially, in an ideal world you're really only meant to use on* from HTML but in an even more ideal world you shouldn't be doing anything like that from HTML.

除非兼容性,您应该作为最佳实践使用 addEventListener。当其他答案谈论这方面的差异而不是基本的程序差异时,我将放弃它。从本质上讲,在理想的世界中,您实际上只打算从 HTML 中使用 on*,但在更理想的世界中,您不应该从 HTML 中执行类似的操作。

Why is it dominant today? It's quicker to write, easier to learn and tends to just work.

为什么它在今天占主导地位?它写起来更快,更容易学习,而且往往能正常工作。

The whole point of onload in HTML is to give access to the addEventListener method or functionality in the first place. By using it in JS you're going through HTML when you could be applying it directly.

HTML 中 onload 的全部意义在于首先访问 addEventListener 方法或功能。通过在 JS 中使用它,当您可以直接应用它时,您正在浏览 HTML。

Hypothetically you can make your own attributes:

假设您可以创建自己的属性:

$('[myclick]').each(function(i, v) {
     v.addEventListener('click', function() {
         eval(v.myclick); // eval($(v).attr('myclick'));
     });
});

What JS does with is a bit different to that.

JS 所做的与此略有不同。

You can equate it to something like (for every element created):

您可以将其等同于(对于创建的每个元素):

element.addEventListener('click', function() {
    switch(typeof element.onclick) {
          case 'string':eval(element.onclick);break;
          case 'function':element.onclick();break;
     }
});

The actual implementation details will likely differ with a range of subtle variations making the two slightly different in some cases but that's the gist of it.

实际的实现细节可能会因一系列细微的变化而有所不同,这使得两者在某些情况下略有不同,但这就是它的要点。

It's arguably a compatibility hack that you can pin a function to an on attribute since by default attributes are all strings.

这可以说是一种兼容性技巧,您可以将函数固定到 on 属性,因为默认情况下属性都是字符串。

回答by Alireza

According to MDN, the difference is as below:

根据MDN,区别如下:

addEventListener:

添加事件监听器:

The EventTarget.addEventListener() method adds the specified EventListener-compatible object to the list of event listeners for the specified event type on the EventTarget on which it's called. The event target may be an Element in a document, the Document itself, a Window, or any other object that supports events (such as XMLHttpRequest).

EventTarget.addEventListener() 方法将指定的与 EventListener 兼容的对象添加到调用它的 EventTarget 上指定事件类型的事件侦听器列表中。事件目标可以是文档中的元素、文档本身、窗口或任何其他支持事件的对象(例如 XMLHttpRequest)。

onclick:

点击:

The onclick property returns the click event handler code on the current element. When using the click event to trigger an action, also consider adding this same action to the keydown event, to allow the use of that same action by people who don't use a mouse or a touch screen. Syntax element.onclick = functionRef; where functionRef is a function - often a name of a function declared elsewhere or a function expression. See "JavaScript Guide:Functions" for details.

onclick 属性返回当前元素上的单击事件处理程序代码。当使用 click 事件触发一个动作时,还要考虑将这个相同的动作添加到 keydown 事件中,以允许不使用鼠标或触摸屏的人使用相同的动作。语法 element.onclick = functionRef; 其中 functionRef 是一个函数——通常是在别处声明的函数的名称或函数表达式。有关详细信息,请参阅“JavaScript 指南:函数”。

There is also a syntax difference in use as you see in the below codes:

addEventListener:

正如您在以下代码中看到的那样,使用中也存在语法差异:

addEventListener:

// Function to change the content of t2
function modifyText() {
  var t2 = document.getElementById("t2");
  if (t2.firstChild.nodeValue == "three") {
    t2.firstChild.nodeValue = "two";
  } else {
    t2.firstChild.nodeValue = "three";
  }
}

// add event listener to table
var el = document.getElementById("outside");
el.addEventListener("click", modifyText, false);

onclick:

点击:

function initElement() {
    var p = document.getElementById("foo");
    // NOTE: showAlert(); or showAlert(param); will NOT work here.
    // Must be a reference to a function name, not a function call.
    p.onclick = showAlert;
};

function showAlert(event) {
    alert("onclick Event detected!");
}

回答by patrik

It should also be possible to either extend the listener by prototyping it (if we have a reference to it and its not an anonymous function) -or make the 'onclick' call a call to a function library (a function calling other functions)

还应该可以通过原型设计来扩展侦听器(如果我们有对它的引用并且它不是匿名函数) - 或者使“onclick”调用调用函数库(调用其他函数的函数)

like

喜欢

    elm.onclick = myFunctionList
    function myFunctionList(){
      myFunc1();
      myFunc2();
    }

this means we never has to chenge the onclick call just alter the function myFunctionList() to do what ever we want, but this leave us without control of bubbling/catching phases so should be avoided for newer browsers.

这意味着我们永远不必更改 onclick 调用,只需更改函数 myFunctionList() 即可执行我们想要的操作,但这使我们无法控制冒泡/捕获阶段,因此应避免在较新的浏览器中使用。

just in case someone find this thread in the future...

以防万一有人在未来找到这个线程......