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

前端 未结 4 923
感动是毒
感动是毒 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 22:51

    Since .live() is simply event delegation, place your handler on the nearest element to the ones being added.

    var container = document.getElementById('my_container');
    
    container.onclick = function(e) {
        e = e || window.event;
        var target = e.target || e.srcElement;
    
        while(target && target.nodeName.toUpperCase() !== 'LI' ) {
            if( target === this )
                target = null;
            else 
                target = target.parentNode;
        }
    
        if( target ) {
            // work with the LI
        }
    };
    

    This is also similar to .live() in the sense that it searches from the e.target up to the container with the delegate to see if it is your targeted element.

    Just testing the e.target itself isn't enough if the li has descendants.


    For more complex analysis of the elements, you could use .matchesSelector, though you'd need to stick it on the HTMLElement.prototype under the correct name, since most browsers include it as an extension.

    Also, you'd need a patch for IE8, but that's pretty easy.

    if (HTMLElement) {
        if (!HTMLElement.prototype.matches && !HTMLElement.prototype.matchesSelector) {
            HTMLElement.prototype.matches =
            HTMLELement.prototype.matchesSelector = 
                HTMLElement.prototype.webkitMatchesSelector ||
                HTMLElement.prototype.mozMatchesSelecvtor ||
                HTMLElement.prototype.msMatchesSelector ||
                HTMLElement.prototype.oMatchesSelector;
        }
    } else if (!Element.prototype.matchesSelector && Element.prototype.querySelectorAll) {
    
        Element.prototype.matches = 
        Element.prototype.matchesSelector =
            function() {
                // exercise for reader to implement using .querySelectorAll, 
                //    though it's pretty easy, and available online if you search
            }
    }
    

提交回复
热议问题