事件冒泡:
元素觸發事件時,會往上冒泡,觸發全部父元素的事件,直接到body
好比:點擊p標籤,會觸發p,div,body對應的事件
e.stopPropagation()能夠阻止向上冒泡,即只會觸發p的對應的事件node
<body>瀏覽器
<div id="div1"> <p id="p1">事件冒泡</p> </div> <script> function bindEvent(elem, type, selector, fn) { if (fn == null) { fn = selector selector = null } elem.addEventListener(type, e=>{ let target if (selector) { target = e.target if (target.matches(selector)) { fn.call(target, e) } } else { fn(e) } }) } const p1 = document.getElementById('p1') const div1 = document.getElementById('div1') const body = document.body bindEvent(p1, 'click', e=>{ // e.stopPropagation() alert('p1事件') }) bindEvent(body, 'click', e=>{ alert('body事件') }) bindEvent(div1, 'click', e=>{ alert('div1事件') }) </script>
</body>code
事件委託:根據事件冒泡原理,給想要加事件元素的父元素增長事件,這樣能夠大大的減小瀏覽器的內存佔用
好比點擊a1,或者a2,都會觸發alert事件
<body>ip
<div id="div1"> <a href="#">a1</a> <a href="#">a2</a> <a href="#">a3</a> <a href="#">a4</a> </div> <script> const div1 = document.getElementById('div1') div1.addEventListener('click', e=>{ e.preventDefault() const target = e.target if (target.nodeName === 'A') { alert(target.innerHTML) } }) </script>
</body>內存