JavaScript之事件委托
1、所谓的事件委托其实就是:
例如ul中有许多li元素,然而我们需要给每个li注册点击事件,非常,不太好处理。这个时候,我们用事件冒泡来处理委托事件,利用target事件对象方法。
<!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> <link rel="stylesheet" href="/js/NES.css"> <link rel="stylesheet" href="/js/style.css"> </head> <body> <div class="lists"> <ul class="nes-list is-disc"> <li>Good morning.</li> <li>Thou hast had a good night's sleep, I hope.</li> <li>Thou hast had a good afternoon</li> <li>Good night.</li> </ul> </div> </body> </html> <script>
//获取ul的dom对象 let ul=document.querySelector('ul');
//给ul注册点击事件 ul.addEventListener('click',function(e) {
//利用冒泡事件流给li变个颜色 e.target.style.backgroundColor='#aaaaaa'; }); </script>