addEventListener和onclick有什么区别?

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

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


当前回答

根据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!");
}

其他回答

onclick基本上是一个addEventListener,当元素被单击时,它专门执行一个函数。当你有一个做简单操作的按钮时,它很有用,比如计算器按钮。addEventlistener可以用于很多事情,比如在加载DOM或所有内容时执行一个操作,类似于window。Onload,但有更多的控制。

注意,实际上可以使用内联使用多个事件,或者至少可以使用onclick,用分号分隔每个函数,例如....

我不会写一个内联函数,因为你可能会有潜在的问题,这将是混乱的imo。只需使用它来调用脚本文件中已经完成的函数。

你用哪一个取决于你想要什么。addEventListener用于复杂操作,onclick用于简单操作。我见过一些项目没有为元素附加一个特定的事件监听器,而是实现了一个更全局的事件监听器,它将确定是否点击了按钮,并根据所按的按钮执行某些任务。在我看来,这可能会导致潜在的问题,尽管很小,可能,资源浪费,如果事件监听器必须处理每一个点击

“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>元素等。

一个细节还没有被注意到:现代桌面浏览器将不同的按钮按下视为AddEventListener的“单击”(默认为“单击”和“onclick”)。

在Chrome 42和IE11上,onclick和AddEventListener都单击左边的fire和中间的click。 在Firefox 38上,onclick只在左键点击时触发,但AddEventListener点击在左、中、右击时触发。

此外,当使用滚动游标时,中键点击行为在浏览器中非常不一致:

在Firefox上,中键单击事件总是会触发。 在Chrome浏览器上,如果中间点击打开或关闭滚动光标,它们不会触发。 在IE上,它们会在滚动光标关闭时触发,但不会在打开时触发。

同样值得注意的是,任何键盘可选择的HTML元素(如input)的“click”事件也会在元素被选中时触发空格或enter。

你也应该考虑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”…读一读吧!