最近公司在做的一个移动门户需要使用 jQuery,但是好久没有用 jQuery 进行开发,着实有点忘记 jQuery 的语法。jQuery 中最推荐的事件绑定方式是用 on 事件,同时利用 on 事件也能完成事件委托。
		因为该移动门户中展示的卡片列表是通过 ajax 获取数据后新生成的元素,所以,要么重新绑定一次事件,要么,进行事件委托,将事件监听绑定在新生成的元素的父元素上面。我采用了第二种方法,也就是利用 on 方法进行事件委托,利用 ul 列表做了简单的测试。
		因为父、子元素均绑定了相同的事件,而新生成的子元素要将事件委托给父元素,所以要在子元素委托的时间中阻止事件冒泡,就不会重复触发事件。
		实例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
   | <!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <meta http-equiv="X-UA-Compatible" content="IE=edge">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <title>Document</title>     <style>         .box{             background-color: blue;             padding: 20px;             width: 200px;         }         .ul{             background-color: #bfa;             padding: 50px;
          }         .li{             background-color: pink;             padding: 20px;             list-style: none;             border-bottom: 1px solid #000;
          }     </style> </head> <body>     <div class="box">         <ul class="ul">             <li class="li">001</li>             <li class="li">002</li>             <li class="li">003</li>             <li class="li">004</li>             <li class="li">005</li>         </ul>     </div>     <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>     <script>         $(".ul").on("click",function(){             console.log("点击了ul")         })                                                                        $(".ul").on("click","li",function(event){                          event.stopPropagation();             console.log("点击了li,事件委托的写法")         })     </script> </body> </html>
   |