最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - addEventListener for new elements - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Jan 14, 2022 at 22:47 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jun 24, 2012 at 17:56 GooglebotGooglebot 15.7k45 gold badges144 silver badges247 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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

http://jsfiddle/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
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 ment of @hemlock, it seems this family of events is deprecated. We have to head towards mutation observers instead.

发布评论

评论列表(0)

  1. 暂无评论