Details of jQuery event delegation (concise)

Event delegation is based on the principle of event bubbling, which uses the parent to trigger the child events.

As shown in the following html, if you do not use event delegation, it is very troublesome to add click event listening to every li.

In addition, if a child node is created dynamically through js, it needs to rebind the event.

With event delegation, you only need to bind an event listener to the parent to bind each li to the corresponding event.

html

<ul id="wrap">
    <li>item1</li>
    <li>item2</li>
    <li>item3</li>
    <li>item4</li>
    <li>item5</li>
</ul>

js

$(function(){

    // Ordinary events
    $('li').click(function(){
        $(this).css('background', '#D4DFE6');
    });


    // Add DOM nodes dynamically
    $('#addBtn').click(function(){
        $(<span class="hljs-string">'#wrap'</span>).append( $('<li>item'+ ($('li').length + 1) +'</li>') );
    });

    /**
     * Event delegation
     */

    // jQuery 1.9 is obsolete
    /*$('li').live('click', function(){
        $(this).css('background', '#D4DFE6');
    });*/

    // delegate writing of jQuery
    $('#wrap').delegate('li', 'click', function(ev){

        // this refers to the delegated object li
        $(this).css('background', '#D4DFE6');

        // Find the parent UL wrap
        $(ev.delegateTarget).css('border', '2px solid #f00');
    });

    // on writing of jQuery
    $('#wrap').on('click', 'li', function(ev) {
        // this refers to the delegated object li
        $(this).css('background', '#D4DFE6');

        // Find the parent UL wrap
        $(ev.delegateTarget).css('border', '2px solid #f00');
    })


    // js Native Writing
    var _wrap = document.getElementById('wrap');
    _wrap.addEventListener('click', function(ev){
        var ev = ev || event;
        if( ev.target.nodeName == 'LI' ) {
            ev.target.style.background = '#8EC0E4';
            console.log( ev.target.innerHTML );
        }

        // Find the parent UL wrap
        this.style.border = '2px solid #f00';
    });

});

----------—– end ----------—–

Source: https://www.jianshu.com/p/847568e6149e

Tags: JQuery

Posted on Thu, 26 Mar 2020 09:32:16 -0700 by shinstar