23.事件委托.html 1.1 KB

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