Native JS equivalent to jQuery delegation

后端 未结 5 1200
予麋鹿
予麋鹿 2020-12-03 08:02

What is the native implementation for event delegation on dynamically created dom elements?

I tried looking at the jQuery source but I can\'t follow the .on

5条回答
  •  死守一世寂寞
    2020-12-03 08:38

    For example, we have such an html structure.

    • item 1
    • item 3
    • item 3

    Note that there is an i tag inside the button.

    If you want to capture exactly the right item for the Click event, you need a function like the one below.

    function delegateClick(selector, callback){
    
        let selectorItems = document.querySelectorAll(selector);
    
        document.addEventListener('click', function(e){
    
            let clickedItems = e.path;
    
            for(let clickedItem of clickedItems){
                for(let selectorItem of selectorItems){
                    if(clickedItem === selectorItem){
    
                        callback(clickedItem);
    
                    }
                }
            }
    
        });
    }
    

    This offers a very similar use to jquery.

    delegateClick('.btn-edit', (elm) => {
    
        //access the clicked DOM element
        elm;       
    
    });
    

提交回复
热议问题