最近维护老的公司项目,jquery中事件累计触发的bug是一个老生长谈的问题,因此想要弄清楚就必须先弄清楚addEventListener和onclick系列方法的区别
W3C上原文如下
addEventListener is the way to register an event listener as specified in W3C DOM. Its benefits are as follows:
- It allows adding more than a single handler for an event. This is particularly useful for DHTML libraries or Mozilla
- extensions that need to work well even if other libraries/extensions are used.
- It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling)
- It works on any DOM element, not just HTML elements.
在一个元素上onclick事件只会触发一次,不能叠加触发,而addEventListener则不一样,会多次注册,然后等点击的时候触发,上述问题的关键原因所在
demo如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
p {
display: inline-block;
width: 100px;
height: 100px;
background: red;
margin-right: 20px;
}
</style>
<body>
<div>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
</div>
</body>
<script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.js"></script>
<script>
function aa() {
// $("p").on("click", function () {
// console.log(222)
// })
*****用jquery出现3次222,所以在这jquery的方法内部,采用的是addEventListener方法*****
// document.getElementsByTagName("p")[0].addEventListener("click", function () {
// console.log(222);
// }, false)
*****使用原生addEventListener()方法,出现3次222*****
document.getElementsByTagName("p")[0].onclick = function () {
console.log(222);
}
*****只会出现一次222*****
}
aa();
aa();
aa();
</script>
</html>