事件冒泡和事件代理

事件冒泡:
元素触发事件时,会往上冒泡,触发全部父元素的事件,直接到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>内存

相关文章
相关标签/搜索