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
其他回答
addEventListener允许您设置多个处理程序,但在IE8或更低版本中不支持。
IE确实有attachEvent,但它并不完全相同。
也可以通过对侦听器进行原型化(如果我们有对它的引用,而且它不是匿名函数)来扩展侦听器,或者使onclick调用成为对函数库的调用(函数调用其他函数)。
如:
elm.onclick = myFunctionList;
function myFunctionList(){
myFunc1();
myFunc2();
}
这意味着我们永远不需要改变onclick调用,只需要改变myFunctionList()函数来做任何我们想做的事情,但这让我们无法控制冒泡/捕获阶段,所以应该避免在新浏览器中使用。
在我的Visual Studio代码中,addEventListener对事件有真实的智能感知
但onclick没有,只有假的
Javascript倾向于把所有东西都混合到对象中,这可能会让人困惑。这就是JavaScript的方式。
本质上,onclick是一个HTML属性。相反,addEventListener是DOM对象上表示HTML元素的方法。
在JavaScript对象中,方法只是一个属性,它有一个函数作为值,并且对它所附加的对象起作用(例如使用这个)。
在JavaScript中,DOM表示的HTML元素将其属性映射到其属性上。
这就是人们感到困惑的地方,因为JavaScript将所有东西都融合到一个单独的容器或名称空间中,没有任何间接层。
在一个正常的OO布局中(它至少合并了属性/方法的命名空间),你可能会有这样的东西:
domElement.addEventListener // Object(Method)
domElement.attributes.onload // Object(Property(Object(Property(String))))
有一些变化,比如它可以为onload使用getter/setter,或者为属性使用HashMap,但最终这就是它的外观。JavaScript消除了这一间接层,期望知道什么是什么。它将domElement和属性合并在一起。
为了限制兼容性,最好使用addEventListener。由于其他答案谈论的是这方面的差异,而不是基本的方案差异,我将放弃它。本质上,在理想的情况下,你只能从HTML中使用on*,但在更理想的情况下,你不应该从HTML中做任何类似的事情。
为什么它在今天占主导地位?这样写起来更快,更容易学习,而且更容易工作。
HTML中onload的全部意义在于首先提供对addEventListener方法或功能的访问。通过在JS中使用它,当你可以直接应用它时,你会通过HTML。
假设你可以创建自己的属性:
$('[myclick]').each(function(i, v) {
v.addEventListener('click', function() {
eval(v.myclick); // eval($(v).attr('myclick'));
});
});
JS所做的与此有点不同。
你可以将它等同于(对于创建的每个元素):
element.addEventListener('click', function() {
switch(typeof element.onclick) {
case 'string':eval(element.onclick);break;
case 'function':element.onclick();break;
}
});
实际的实现细节可能会有所不同,有一系列微妙的变化,使两者在某些情况下略有不同,但这是它的要点。
这可以说是一种兼容性hack,您可以将一个函数固定到一个on属性,因为默认属性都是字符串。
虽然onclick可以在所有浏览器中工作,但addEventListener不能在旧版本的Internet Explorer中工作,后者使用attachEvent代替。
onclick的缺点是只能有一个事件处理程序,而其他两个将触发所有注册的回调。