1. 程式人生 > >jquery中一個點選事件累計觸發問題詳解。

jquery中一個點選事件累計觸發問題詳解。

最近維護老的公司專案,jquery中事件累計觸發的bug是一個老生長談的問題,因此想要弄清楚就必須先弄清楚addEventListeneronclick系列方法的區別


W3C上原文如下

addEventListener is the way to register an event listener as specified in W3C DOM. Its benefits are as follows:

  1. It allows adding more than a single handler for an event. This is particularly useful for DHTML libraries or Mozilla
  2. extensions that need to work well even if other libraries/extensions are used.
  3. It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling)
  4. 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出現3222,所以在這jquery的方法內部,採用的是addEventListener方法***** // document.getElementsByTagName("p")[0].addEventListener("click", function () { // console.log(222); // }, false) *****使用原生addEventListener()方法,出現3222***** document.getElementsByTagName("p")[0].onclick = function () { console.log(222); } *****只會出現一次222***** } aa(); aa(); aa(); </script> </html>
補充:jquery這樣問題的解決辦法是在進行新的事件註冊時,先要使用$(selector).off()進行事件解綁,然後再進行事件註冊