addEventListener和onclick有什么区别?
var h = document.getElementById("a");
h.onclick = dothing1;
h.addEventListener("click", dothing2);
上面的代码一起驻留在一个单独的.js文件中,它们都可以完美地工作。
addEventListener和onclick有什么区别?
var h = document.getElementById("a");
h.onclick = dothing1;
h.addEventListener("click", dothing2);
上面的代码一起驻留在一个单独的.js文件中,它们都可以完美地工作。
当前回答
在这个回答中,我将描述定义DOM事件处理程序的三种方法。
element.addEventListener()
代码示例:
const element = document.querySelector('a'); 元素。addEventListener('click', event => event. preventdefault (), true); <a href="//google.com">试着点击这个链接
addeventlistener()有多个优点:
Allows you to register unlimited events handlers and remove them with element.removeEventListener(). Has useCapture parameter, 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 does matter 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 .onevent properties of DOM elements, lots of inexperienced JavaScript programmers thinks that the event name is for example onclick or onload. on is not a part of event name. Correct event names are click and 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.
元素。Onevent = function(){}(例如onclick, onload)
代码示例:
const element = document.querySelector('a'); 元素。onclick = event => event. preventdefault (); <a href="//google.com">试着点击这个链接
这是在DOM 0中注册事件处理程序的一种方法。现在不鼓励这样做,因为:
Allows you to register only one event handler. Also removing the assigned handler is not intuitive, because to remove event handler assigned using this method, you have to revert onevent property back to its initial state (i.e. null). Doesn't respond to errors appropriately. 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 HTML属性)
代码示例:
<a href="//google.com" onclick="event.preventDefault();>试着点击这个链接
类似于element。Onevent,现在不鼓励了。除了那个元素的问题。Onevent有,它:
Is a potential security issue, because it makes XSS much more harmful. Nowadays websites should send proper Content-Security-Policy HTTP 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.
另请参阅
EventTarget.addEventListener()文档(MDN) EventTarget.removeEventListener()文档(MDN) onclick vs addEventListener Dom-events标记wiki
其他回答
“this”关键字在JavasSript中引用的上下文是不同的。
请看下面的代码:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<input id="btnSubmit" type="button" value="Submit" />
<script>
function disable() {
this.disabled = true;
}
var btnSubmit = document.getElementById('btnSubmit');
btnSubmit.onclick = disable();
//btnSubmit.addEventListener('click', disable, false);
</script>
</body>
</html>
它的功能非常简单。当您点击该按钮时,该按钮将自动禁用。
首先,当您尝试以这种方式按钮连接事件时。Onclick = function(), 点击按钮会触发Onclick事件,但是,按钮不会被禁用,因为按钮之间没有显式的绑定。Onclick和Onclick事件处理器。如果你调试看到'this'对象,你可以看到它指向'window'对象。
其次,如果你评论btnSubmit。Onclick =禁用();和取消 / / btnSubmit。addEventListener('点击',禁用,false);您可以看到按钮是禁用的,因为通过这种方式,按钮之间有显式绑定。点击事件和点击事件处理程序。如果你调试为禁用功能,你可以看到“this”指的是按钮控件而不是窗口。
这是我不喜欢JavaScript不一致的地方。 顺便说一句,如果你使用jQuery($('#btnSubmit')。On ('click', disable);),它使用显式绑定。
元素。Onclick = function() {/* do stuff */} 元素。addEventListener('click', function(){/* do stuff */},false);
它们显然做同样的事情:监听click事件并执行回调函数。然而,它们是不相等的。如果你需要在两者之间做出选择,这可以帮助你弄清楚哪一个最适合你。
主要的区别是onclick只是一个属性,像所有对象属性一样,如果你写了多次,它将被覆盖。而使用addEventListener(),我们可以简单地将事件处理程序绑定到元素,并且可以在每次需要时调用它,而不用担心任何重写的属性。 例子如下,
试试吧:https://jsfiddle.net/fjets5z4/5/
首先,我想继续使用onclick,因为它更短,看起来更简单,事实上也是如此。但我不建议再使用它了。这就像使用内联JavaScript一样。使用内联JavaScript之类的东西现在是非常不鼓励的(内联CSS也是不鼓励的,但这是另一个话题)。
然而,addEventListener()函数尽管是标准的,但在旧的浏览器(Internet Explorer低于版本9)中不能工作,这是另一个很大的区别。如果您需要支持这些古老的浏览器,您应该遵循onclick方式。但是你也可以使用jQuery(或它的替代品之一):它基本上简化了你的工作,减少了浏览器之间的差异,因此可以节省你很多时间。
var clickEvent = document.getElementByID("onclick-eg");
var EventListener = document.getElementByID("addEventListener-eg");
clickEvent.onclick = function(){
window.alert("1 is not called")
}
clickEvent.onclick = function(){
window.alert("1 is not called, 2 is called")
}
EventListener.addEventListener("click",function(){
window.alert("1 is called")
})
EventListener.addEventListener("click",function(){
window.alert("2 is also called")
})
这两种方法都是正确的,但没有一种方法本身是“最好的”,开发人员选择使用这两种方法可能是有原因的。
《捉鬼列表和衰人》
早期版本的Internet Explorer对JavaScript的实现与其他浏览器几乎不同。对于小于9的版本,您使用attachEvent[doc]方法,如下所示:
element.attachEvent('onclick', function() { /* do stuff here*/ });
在大多数其他浏览器(包括ie9及以上)中,您使用addEventListener[doc],如下所示:
element.addEventListener('click', function() { /* do stuff here*/ }, false);
使用这种方法(DOM Level 2事件),理论上可以将无限数量的事件附加到任何单个元素。唯一的实际限制是客户端内存和其他性能问题,这对于每个浏览器都是不同的。
上面的例子表示使用匿名函数[doc]。你也可以使用函数引用[doc]或闭包[doc]来添加事件监听器:
var myFunctionReference = function() { /* do stuff here*/ }
element.attachEvent('onclick', myFunctionReference);
element.addEventListener('click', myFunctionReference , false);
addEventListener的另一个重要特性是final参数,它控制监听器如何对冒泡事件做出反应。我在示例中传递了false,这可能是95%用例的标准。对于attachEvent,或者在使用内联事件时,没有等效的参数。
内联事件(HTML onclick=""属性和元素。onclick)
在所有支持javascript的浏览器中,您都可以将事件监听器内联,也就是在HTML代码中。你可能看过这个:
<a id="testing" href="#" onclick="alert('did stuff inline');">Click me</a>
大多数有经验的开发人员都避免使用这种方法,但它确实可以完成工作;它简单直接。这里您不能使用闭包或匿名函数(尽管处理程序本身是某种匿名函数),而且您对作用域的控制是有限的。
你提到的另一种方法:
element.onclick = function () { /*do stuff here */ };
... 它相当于内联javascript,只不过你可以更好地控制作用域(因为你写的是脚本而不是HTML),并且可以使用匿名函数、函数引用和/或闭包。
内联事件的显著缺点是,与上面描述的事件侦听器不同,您可能只分配了一个内联事件。内联事件存储为元素[doc]的属性/属性,这意味着它可以被覆盖。
使用上面HTML中的例子<a>:
var element = document.getElementById('testing');
element.onclick = function () { alert('did stuff #1'); };
element.onclick = function () { alert('did stuff #2'); };
... 当你点击元素时,你只会看到“Did stuff #2”——你用第二个值覆盖了onclick属性的第一个赋值,你也覆盖了原始的HTML内嵌onclick属性。点击这里查看:http://jsfiddle.net/jpgah/。
一般来说,不要使用内联事件。它可能有特定的用例,但是如果您不能100%确定您有这个用例,那么您就不应该也不应该使用内联事件。
现代Javascript (Angular之类的)
自从这个答案最初发布以来,像Angular这样的javascript框架已经变得更加流行。你会在Angular模板中看到这样的代码:
<button (click)="doSomething()">Do Something</button>
这看起来像一个内联事件,但它不是。这种类型的模板将转换为更复杂的代码,在幕后使用事件侦听器。我在这里所写的关于事件的所有内容仍然适用,但你至少从本质上被移除了一层。您应该了解具体细节,但如果您的现代JS框架最佳实践涉及在模板中编写这类代码,不要觉得您在使用内联事件——您不是。
哪个是最好的?
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.
jQuery和其他javascript框架将DOM级别2事件的不同浏览器实现封装在通用模型中,这样您就可以编写跨浏览器兼容的代码,而不必担心IE的反叛历史。相同的代码与jQuery,所有跨浏览器和准备摇滚:
$(element).on('click', function () { /* do stuff */ });
但是,不要仅仅为了这一件事而去找一个框架。你可以很容易地使用自己的小工具来处理旧的浏览器:
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版本中工作。
文档及相关阅读
W3 HTML规范,元素事件处理程序属性 元素。addEventListener在MDN 元素。attachEvent在MSDN上 Jquery.on quirksmode博客“事件介绍” cdn托管的javascript库在谷歌
根据MDN,差异如下:
addEventListener:
EventTarget.addEventListener()方法添加指定的 对象的事件侦听器列表中的 在调用它的EventTarget上指定的事件类型。的 事件目标可以是文档中的一个元素,文档本身,一个 窗口或任何其他支持事件的对象(例如 XMLHttpRequest)。
onclick:
属性上的单击事件处理程序代码 当前元素。当使用click事件触发操作时,也是如此 考虑将相同的操作添加到keydown事件,以允许 不使用鼠标或触摸的人使用相同的动作 屏幕上。语法元素。onclick = functionRef;where functionRef是a 函数——通常是在别处声明的函数名或函数名 表达式。详见“JavaScript指南:函数”。
在使用中也有语法差异,你可以在下面的代码中看到: 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!");
}
一个元素对每种事件类型只能有一个事件处理程序,但可以有多个事件监听器。
那么,它的实际情况如何呢?
只有最后分配的事件处理程序才会运行:
const button = document.querySelector(".btn")
button.onclick = () => {
console.log("Hello World");
};
button.onclick = () => {
console.log("How are you?");
};
button.click() // "How are you?"
所有事件监听器将被触发:
const button = document.querySelector(".btn")
button.addEventListener("click", event => {
console.log("Hello World");
})
button.addEventListener("click", event => {
console.log("How are you?");
})
button.click()
// "Hello World"
// "How are you?"
IE注:attachEvent不再支持。从IE 11开始,使用addEventListener: docs。