jquery中一個點選事件累計觸發問題詳解。
阿新 • • 發佈:2018-11-09
最近維護老的公司專案,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>