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文件中,它们都可以完美地工作。
当前回答
一个元素对每种事件类型只能有一个事件处理程序,但可以有多个事件监听器。
那么,它的实际情况如何呢?
只有最后分配的事件处理程序才会运行:
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。
其他回答
addEventListener允许您设置多个处理程序,但在IE8或更低版本中不支持。
IE确实有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上运行得很好,并且可能有一些关于“绑定”与其他浏览器兼容的问题。
在我的Visual Studio代码中,addEventListener对事件有真实的智能感知
但onclick没有,只有假的
一个细节还没有被注意到:现代桌面浏览器将不同的按钮按下视为AddEventListener的“单击”(默认为“单击”和“onclick”)。
在Chrome 42和IE11上,onclick和AddEventListener都单击左边的fire和中间的click。 在Firefox 38上,onclick只在左键点击时触发,但AddEventListener点击在左、中、右击时触发。
此外,当使用滚动游标时,中键点击行为在浏览器中非常不一致:
在Firefox上,中键单击事件总是会触发。 在Chrome浏览器上,如果中间点击打开或关闭滚动光标,它们不会触发。 在IE上,它们会在滚动光标关闭时触发,但不会在打开时触发。
同样值得注意的是,任何键盘可选择的HTML元素(如input)的“click”事件也会在元素被选中时触发空格或enter。
一个元素对每种事件类型只能有一个事件处理程序,但可以有多个事件监听器。
那么,它的实际情况如何呢?
只有最后分配的事件处理程序才会运行:
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。