17_事件委托.html 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 list1 = document.getElementById('list1')
  18. var btn = document.getElementById('btn')
  19. var aLi = document.getElementsByTagName('li')
  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 a = document.createElement('li')
  27. a.innerHTML = Math.random()
  28. list1.appendChild(a)
  29. // console.log(this)
  30. }
  31. list1.onclick = function(e){
  32. // console.log(e.target.tagName)
  33. if(e.target.tagName == 'LI'){
  34. console.log(e.target.innerHTML)
  35. }
  36. console.log(this)
  37. }
  38. </script>
  39. </body>
  40. </html>