1.事件委托.html 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. <!--
  10. 事件委托:
  11. 减少内存消耗 避免多次循环
  12. -->
  13. <ul id="list">
  14. <li>1</li>
  15. <li>2</li>
  16. <li>3</li>
  17. <li>4</li>
  18. </ul>
  19. <button class="btn">添加</button>
  20. <script>
  21. var list = document.getElementById("list");
  22. var lists = document.querySelectorAll("#list li");
  23. var btn = document.getElementsByClassName("btn")[0];
  24. // console.log(btn)
  25. btn.onclick = function() {
  26. var li1 = document.createElement("li");
  27. console.log(li1)
  28. li1.innerText = Math.round(Math.random()*9+1);
  29. list.appendChild(li1);
  30. }
  31. list.onclick = function(event) {
  32. console.log(event)
  33. if(event.target.nodeName == 'LI') {
  34. console.log(event.target.innerText)
  35. }
  36. }
  37. // lists.onclick = function(event) {
  38. // console.log(event,'121')
  39. // }
  40. // console.log(lists)
  41. </script>
  42. </body>
  43. </html>