addEventListener和onclick有什么区别?

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

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


当前回答

元素。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")
})

其他回答

在这个回答中,我将描述定义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方法从这个角度来看更安全。当然,您可以使用unsafe-inline来启用内联处理程序,但是,顾名思义,它并不安全,因为它会带来CSP阻止的大量JavaScript漏洞。

你也应该考虑eventdelegate ! 因此,我更喜欢addEventListener,最重要的是小心谨慎地使用它!

事实:

eventlistener是沉重的....(客户端内存分配) 事件在与DOM的关系中传播IN,然后再次传播OUT 树。也被称为涓滴式和冒泡式,读一读 以防你不知道。

想象一个简单的例子: 一个简单的按钮内部div内部主体… 如果你点击按钮,一个事件将无论如何 滴入到BUTTON,然后再OUT,像这样:

window-document-div-button-div-document-window

在浏览器后台(比如JS引擎的软件外围),浏览器只能对点击做出反应,如果它检查了每一次点击的目标位置。

为了确保每个可能的事件监听器都被触发,它必须从文档级别一直发送“点击事件信号”到元素中。然后再回来。 这个行为可以通过附加eventlistener来使用,例如:

document.getElementById("exampleID").addEventListener("click",(event) => {doThis}, true/false);

请注意,作为addEventListener方法最后一个参数的true/false控制了何时识别事件的行为——何时流入或何时流出。

TRUE表示事件在传入时被识别 FALSE表示事件在冒泡输出的过程中被识别

实现以下2个有用的概念,使用上述方法处理问题也会更加直观:

You can also use event.stopPropagation() within the function (example ref. "doThis") to prevents further propagation of the current event in the capturing and bubbling phases. It does not, however, prevent any default behaviors from occurring; for instance, clicks on links are still processed. If you want to stop those behaviors, you could use event.preventDefault() within the function (example ref. "doThis"). With that you could for example tell the Browser that if the event does not get explicitly handled, its default action should not be taken as it normally would be.

还需要再次注意这里的参考:addEventListener方法的最后一个参数(true/false)也控制了“. stoppropagation()”的最终效果在哪个阶段生效(涓滴为true或冒头为false)。 所以…如果你将一个带有TRUE标志的EventListener应用到一个元素,并将其与.stopPropagation()方法结合起来,事件甚至不会通过元素的潜在内部子元素

总结一下: 如果你在HTML中使用onClick变体…对我来说有两个缺点:

与addEventListener,你可以附加多个onClick事件到相同的,分别是一个单一的元素,但这是不可能使用onClick(至少这是我坚信到目前为止,如果我错了,请纠正我)。 以下方面也确实值得注意……特别是代码维护部分(到目前为止还没有详细说明):

In regards to event delegation, it really boils down to this. If some other JavaScript code needs to respond to a click event, using addEventListener ensures you both can respond to it. If you both try using onclick, then one stomps on the other. You both can't respond if you want an onclick on the same element. Furthermore, you want to keep your behavior as separate as you can from the HTML in case you need to change it later. It would suck to have 50 HTML files to update instead of one JavaScript file. (credit to Greg Burghardt, addEventListener vs onclick with regards to event delegation )

这也被称为“Unobtrusive JavaScript”…读一读吧!

“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);),它使用显式绑定。

据我所知,DOM“加载”事件仍然只发挥非常有限的作用。这意味着它只会触发窗口对象,图像和<script>元素。直接onload赋值也是如此。这两者在技术上没有区别。也许.onload =具有更好的跨浏览器可用性。

但是,您不能将加载事件分配给<div>或<span>元素等。