addEventListener和onclick有什么区别?

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

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


当前回答

一个元素对每种事件类型只能有一个事件处理程序,但可以有多个事件监听器。


那么,它的实际情况如何呢?

只有最后分配的事件处理程序才会运行:

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。

其他回答

虽然onclick可以在所有浏览器中工作,但addEventListener不能在旧版本的Internet Explorer中工作,后者使用attachEvent代替。

onclick的缺点是只能有一个事件处理程序,而其他两个将触发所有注册的回调。

如果你有另外两个函数,你可以看到区别:

var h = document.getElementById('a');
h.onclick = doThing_1;
h.onclick = doThing_2;

h.addEventListener('click', doThing_3);
h.addEventListener('click', doThing_4);

函数2、3和4可以工作,但函数1不行。这是因为addEventListener不会覆盖现有的事件处理程序,而onclick会覆盖任何现有的onclick = fn事件处理程序。

当然,另一个重要的区别是onclick总是可以工作,而addEventListener在版本9之前的ie中不能工作。你可以在IE <9中使用类似的attachEvent(语法略有不同)。

如果你不太担心浏览器的支持,有一种方法可以在事件调用的函数中重新绑定'this'引用。它通常指向在函数执行时生成事件的元素,这并不总是您想要的。棘手的部分是同时能够删除相同的事件侦听器,如本例所示:http://jsfiddle.net/roenbaeck/vBYu3/

/*
    Testing that the function returned from bind is rereferenceable, 
    such that it can be added and removed as an event listener.
*/
function MyImportantCalloutToYou(message, otherMessage) {
    // the following is necessary as calling bind again does 
    // not return the same function, so instead we replace the 
    // original function with the one bound to this instance
    this.swap = this.swap.bind(this); 
    this.element = document.createElement('div');
    this.element.addEventListener('click', this.swap, false);
    document.body.appendChild(this.element);
}
MyImportantCalloutToYou.prototype = {
    element: null,
    swap: function() {
        // now this function can be properly removed 
        this.element.removeEventListener('click', this.swap, false);           
    }
}

上面的代码在Chrome上运行得很好,并且可能有一些关于“绑定”与其他浏览器兼容的问题。

我想Chris Baker在一个很好的答案中总结了它,但我想添加到addEventListener()中,你也可以使用options参数,它可以让你更好地控制你的事件。例如,如果你只想运行你的事件一次,那么你可以在添加事件时使用{once: true}作为一个选项参数,只调用它一次。

    function greet() {
    console.log("Hello");
    }   
    document.querySelector("button").addEventListener('click', greet, { once: true })

上面的函数只打印“Hello”一次。 此外,如果你想清理你的事件,那么还有removeEventListener()选项。虽然使用addEventListener()有优点,但如果您的目标受众使用Internet Explorer,则此方法可能并不适用于所有情况,您仍然应该小心。你也可以在MDN上读到addEventListener,他们对如何使用它们给出了很好的解释。

addEventListener允许您设置多个处理程序,但在IE8或更低版本中不支持。

IE确实有attachEvent,但它并不完全相同。