0173 event delegation: principle, function

Event bubbling own characteristics, will bring harm, also benefits.

1.3.8.1 What is the event delegate

Event delegates: also known as event agency, which called event delegation in jQuery.

把事情委托给别人,代为处理。

It means, do not give the child elements to register an event, the parent element to register an event, the event handling code execution in the parent element.


Life agent:


js events agency:


Principle 1.3.8.2 event delegate

Sign up event to the parent element, use event bubbling, when the event triggering the child elements will bubble up to the parent element, and then to control the corresponding sub-element [use event bubbling affect each child node].


1.3.8.3 event delegate role

  • We only operate a DOM, improve program performance.

  • Dynamic newly created sub-elements, also has events.

    <ul>
        <li>知否知否,点我应有弹框在手1111!</li>
        <li>知否知否,点我应有弹框在手2222!</li>
        <li>知否知否,点我应有弹框在手3333!</li>
        <li>知否知否,点我应有弹框在手4444!
            <!-- 加的3行代码。【经试验,孙子级的元素也一样起作用】 -->
            <div>aaa</div>
            <div>bbb</div>
            <div>ccc</div>
        </li>
        <li>知否知否,点我应有弹框在手5555!</li>
    </ul>
    <script>
        // 事件委托的核心原理:给父节点添加侦听器, 利用事件冒泡影响每一个子节点
        var ul = document.querySelector('ul');

        // 点击的是li,li冒泡,往上传给ul,ul也绑定了点击事件,于是执行相应代码。
        ul.addEventListener('click', function(e) {
            // alert('知否知否,点我应有弹框在手!');
            // e.target 这个可以得到我们点击的对象
            e.target.style.backgroundColor = 'pink';
        })
    </script>

Guess you like

Origin www.cnblogs.com/jianjie/p/12177882.html