17_事件委托.html 1009 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <ul id="list1">
  11. <li>1</li>
  12. <li>2</li>
  13. <li>3</li>
  14. </ul>
  15. <button id="btn">按钮</button>
  16. <script>
  17. var aLi = document.getElementsByTagName('li')
  18. var list1 = document.getElementById('list1')
  19. var btn = document.getElementById('btn')
  20. // for (var i = 0; i < aLi.length; i++) {
  21. // aLi[i].onclick = function(){
  22. // console.log(this.innerHTML)
  23. // }
  24. // }
  25. btn.onclick = function () {
  26. var xx = document.createElement('li')
  27. xx.innerHTML = Math.random()
  28. list1.appendChild(xx)
  29. }
  30. list1.onclick = function (e) {
  31. // console.log(e.target.tagName)
  32. if (e.target.tagName == 'LI') {
  33. console.log(e.target.innerHTML)
  34. }
  35. // console.log(this)
  36. }
  37. </script>
  38. </body>
  39. </html>