addEventListener for new elements

岁酱吖の 提交于 2019-12-22 08:32:21

问题


Consider a basic addEventListener as

window.onload=function(){
  document.getElementById("alert")
  .addEventListener('click', function(){
     alert("OK");
  }, false);
}

where <div id="alert">ALERT</div> does not exist in the original document and we call it from an external source by AJAX. How we can force addEventListener to work for newly added elements to the documents (after initial scan of DOM elements by window.onload)?

In jQuery, we do this by live() or delegate(); but how we can do this with addEventListener in pure Javascript? As a matter of fact, I am looking for the equivalent to delegate(), as live() attaches the event to the root document; I wish to make a fresh event listening at the level of parent.


回答1:


Overly simplified and is very far away from jQuery's event system but the basic idea is there.

http://jsfiddle.net/fJzBL/

var div = document.createElement("div"),
    prefix = ["moz","webkit","ms","o"].filter(function(prefix){
         return prefix+"MatchesSelector" in div;
    })[0] + "MatchesSelector";

Element.prototype.addDelegateListener = function( type, selector, fn ) {

    this.addEventListener( type, function(e){
        var target = e.target;

        while( target && target !== this && !target[prefix](selector) ) {
            target = target.parentNode;
        }

        if( target && target !== this ) {
            return fn.call( target, e );
        }

    }, false );
};

What you are missing on with this:

  • Performance optimizations, every delegate listener will run a full loop so if you add many on a single element, you will run all these loops
  • Writable event object. So you cannot fix e.currentTarget which is very important since this is usually used as a reference to some instance
  • There is no data store implementation so there is no good way to remove the handlers unless you make the functions manually everytime
  • Only bubbling events are supported, so no "change" or "submit" etc which you took for granted with jQuery
  • Many others which I'm simply forgetting about for now



回答2:


document.addEventListener("DOMNodeInserted", evtNewElement, false);

function evtNewElement(e) {
    try {
        switch(e.target.id) {
            case 'alert': /* addEventListener stuff */ ; break;
            default: /**/
        }
    } catch(ex) {}
}

Note: according to the comment of @hemlock, it seems this family of events is deprecated. We have to head towards mutation observers instead.



来源:https://stackoverflow.com/questions/11179841/addeventlistener-for-new-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!