Onclick vs addEventListener [英] Onclick vs addEventListener

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

问题描述


可能重复:

addeventhandler vs onclick

我没有使用onclick迷惑作为HTML元素的财产。

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

如:

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

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

推荐答案

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

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"

另请注意

虽然所有浏览器,addEventListener在旧版本的Internet Explorer中不起作用,该版本使用attachEvent。

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

OnClick 是一个 DOM Level 0 属性。 AddEventListener DOM Level 2 定义的一部分。请阅读: http://www.w3.org/TR /DOM-Level-2-Events/events.html

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

内嵌事件处理程序作为HTML标签属性添加,例如:

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

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

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

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.

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

提高此:您可以添加多个事件处理程序。还有separte html和javascript代码

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

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

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

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

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