19.事件委托.html 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <ul>
  10. <li>11</li>
  11. <li>22</li>
  12. <li>33</li>
  13. <li>44</li>
  14. <p>87878</p>
  15. <li>55</li>
  16. </ul>
  17. <button>添加</button>
  18. <script>
  19. var btn = document.querySelector("button")
  20. var uls = document.querySelector("ul");
  21. var list = document.querySelectorAll("ul li");
  22. // 事件委托:减少内存消耗 避免多次循环
  23. // for(var i=0;i<list.length;i++) {
  24. // list[i].onclick = function(){
  25. // console.log(this)
  26. // }
  27. // }
  28. uls.onclick = function(event) {
  29. if(event.target.nodeName == 'LI') {
  30. console.log(event.target.innerText,'www')
  31. }
  32. }
  33. btn.onclick = function() {
  34. var li1 = document.createElement("li");
  35. li1.innerText = '大家好';
  36. uls.appendChild(li1)
  37. }
  38. </script>
  39. </body>
  40. </html>