Javascript Onclick 与 addEventListener

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

Onclick vs addEventListener

javascripteventsaddeventlistener

提问by Paul Brewczynski

I'm little confusing by using "onclick" "onmousedown" as a property of HTML elements.

通过使用“onclick”“onmousedown”作为 HTML 元素的属性,我有点困惑。

Such as:

如:

<button onclick="my_JS_function()"></button>

or

或者

<div onmousedown="my_another_JS_funciton"></div>

But some people tell that only "proper" way of adding "listeners" are by

但是有些人说只有添加“听众”的“正确”方式是通过

document.getElementById("my_id").addEventListener("onclick", my_JS_function, false);

What is the more "proper" more supported way of doing that?

什么是更“正确”更受支持的方式?

回答by Pranay Rana

if you already know function and element is part of html i.e. not get added dynamically than its good that you add function inline rather than using extra method call like "addEventListener"

如果您已经知道函数和元素是 html 的一部分,即不要动态添加,而不是添加内联函数而不是使用像“addEventListener”这样的额外方法调用

Another thing to note

还有一点要注意

While onclick works in all browsers, addEventListener does not work in older versions of Internet Explorer, which uses attachEvent instead.

虽然onclick 适用于所有浏览器,但 addEventListener 在旧版本的 Internet Explorer 中不起作用,它使用 attachEvent 代替。

OnClickis a DOM Level 0property. AddEventListeneris part of the DOM Level 2definition. Read about this : http://www.w3.org/TR/DOM-Level-2-Events/events.html

OnClickDOM 级别 0属性。AddEventListenerDOM Level 2定义的一部分。阅读此内容:http: //www.w3.org/TR/DOM-Level-2-Events/events.html

inline event handlers added as HTML tag attributes, for example:

作为 HTML 标记属性添加的内联事件处理程序,例如:

 <a href="gothere.htm" onlick="alert('Bye!')">Click me!</a> 

The above techniques are simple but have certain disadvantages: they allow you to have just one event handler per element. In addition, with inline event handlers you get very poor separation of JavaScript code from HTML markup.

上述技术很简单,但有一些缺点:它们允许每个元素只有一个事件处理程序。此外,使用内联事件处理程序,您无法将 JavaScript 代码与 HTML 标记分离。

document.getElementById("my_id").addEventListener("onclick", my_JS_function, false);

Advatange of this: you can add multiple event handler. also separte html and javascript code

这样做的好处:您可以添加多个事件处理程序。也分开 html 和 javascript 代码

For more detail you can read this : Adding an Event Handler

有关更多详细信息,您可以阅读:添加事件处理程序

回答by alex

The latter (addEventListener()) is the best way, as you can attach multiple events of the same type to the same element.

后者 ( addEventListener()) 是最好的方法,因为您可以将多个相同类型的事件附加到同一个元素。

By assigning to onclick, etc, you will overwrite existing handlers.

通过分配 toonclick等,您将覆盖现有的处理程序。