带你读《现代Javascript高级教程》八、JavaScript事件流:深入理解事件处理和传播机制(2)https://developer.aliyun.com/article/1349640?groupCode=tech_library
4. 示例代码
下面是一些示例代码,演示了事件流的应用和相关的属性:
<button id="myButton">点击按钮</button><ul id="myList"> <li>项目1</li> <li>项目2</li> <li>项目3</li></ul><div id="myContainer"> <button class="button">按钮</button> <a href="" class="link">链接</a></div> <script> // 事件处理示例 const button = document.getElementById('myButton'); button.addEventListener('click', function(event) { console.log('按钮被点击'); }); // 事件代理示例 const list = document.getElementById('myList'); list.addEventListener('click', function(event) { if (event.target.tagName === 'LI') { console.log('项目被点击'); } }); // 事件委托示例 const container = document.getElementById('myContainer'); container.addEventListener('click', function(event) { if (event.target.classList.contains('button')) { console.log('按钮被点击'); } else if (event.target.classList.contains('link')) { console.log('链接被点击'); } });</script>
5. 参考资料
- MDN Web Docs - Event referenceopen in new window
- MDN Web Docs - Introduction to eventsopen in new window
- JavaScript.info - Bubbling and capturingopen in new window
- W3Schools - JavaScript HTML DOM EventListener