js_practice_5.html 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>给多个元素绑定事件</title>
  6. <style>
  7. #buttons>button {
  8. border: none;
  9. outline: none;
  10. width: 120px;
  11. height: 40px;
  12. font: 22px/40px Arial;
  13. background-color: red;
  14. color: white;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="buttons">
  20. <button><input type="checkbox" disabled>苹果</button>
  21. <button><input type="checkbox" disabled>香蕉</button>
  22. <button><input type="checkbox" disabled>草莓</button>
  23. <button><input type="checkbox" disabled>蓝莓</button>
  24. <button><input type="checkbox" disabled>榴莲</button>
  25. <button><input type="checkbox" disabled>西瓜</button>
  26. <button><input type="checkbox" disabled>芒果</button>
  27. <button><input type="checkbox" disabled>柠檬</button>
  28. </div>
  29. <script src="js/hello.js"></script>
  30. <script>
  31. const allButtons = document.querySelectorAll('#buttons>button')
  32. allButtons.forEach(button => {
  33. button.addEventListener('click', () => {
  34. let checkbox = button.firstChild
  35. checkbox.checked = !checkbox.checked
  36. // button.style.backgroundColor =
  37. // checkbox.checked? 'green' : 'red'
  38. button.style.backgroundColor = randomColor()
  39. })
  40. })
  41. // textContent / innerHTML
  42. // image.src / image.title / image.style / checkbox.checked
  43. // ES6的做法:
  44. // for (let i = 0; i < allButtons.length; i += 1) {
  45. // // 闭包(closure) - 将一个块级作用域的变量生命周期延长至了全局
  46. // allButtons[i].addEventListener('click', () => {
  47. // let checkbox = allButtons[i].firstChild
  48. // checkbox.checked = !checkbox.checked
  49. // allButtons[i].style.backgroundColor =
  50. // checkbox.checked? 'green' : 'red'
  51. // })
  52. // }
  53. // ES5的做法:
  54. // for (var i = 0; i < allButtons.length; i += 1) {
  55. // allButtons[i].addEventListener('click', function(evt) {
  56. // // 我们知道事件发生时要做什么但我们不知道事件什么时候发生
  57. // // 在这种情况下就需要放置一个回调函数(callback function)
  58. // // 绑定事件时传入的函数通常我们称之为回调函数
  59. // // 当浏览器执行该回调函数时会传入一个代表事件的对象
  60. // 通过事件对象的target属性就可以获取到事件源(谁引发了事件)
  61. // var checkbox = evt.target.firstChild
  62. // checkbox.checked = !checkbox.checked
  63. // evt.target.style.backgroundColor =
  64. // checkbox.checked? 'green' : 'red'
  65. // })
  66. //}
  67. </script>
  68. </body>
  69. </html>