How to apply live() like feature for JavaScript appended DOM elements

前端 未结 4 925
感动是毒
感动是毒 2021-01-16 22:23

How to apply live() like feature for JavaScript appended DOM elements?

Like a li list inside ul which is added through JavaScr

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-16 23:09

    You have to bind an event to the document root, and check the event.target property. If it matches the given selector, then do something.

    Example (assuming addEventListener)
    Example: Match all elements with id test:

    var root = document.documentElement;
    root.addEventListener('click', function(event) {
        var target = event.target;          // <-- Clicked element
        while (target && target !== root) { // Tree traversing
            if (target.id == 'test') {      // <------ Matches selector
                // Do something.
                break; // Optional: Stop traversal, because a match has been found
    
            }
            target = target.parentNode; // Go up in the tree
        }
    }, true);
    

提交回复
热议问题