jquery中一个点击事件累计触发问题详解。

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Mr_YanYan/article/details/80882424

最近维护老的公司项目,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()进行事件解绑,然后再进行事件注册

猜你喜欢

转载自blog.csdn.net/Mr_YanYan/article/details/80882424