Is there a jquery event that fires when a new node is inserted into the dom?

后端 未结 5 1671
故里飘歌
故里飘歌 2020-11-27 04:05

Is there an event jquery fires on a dom element when it is inserted into the dom?

E.g. lets say I load some content via ajax and add it to the DOM and in some other

5条回答
  •  醉梦人生
    2020-11-27 05:05

    If you're living on the cutting edge you can use MutationObserver :)

      var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
      var list = document.querySelector('ol');
    
      var observer = new MutationObserver(function(mutations) {  
        mutations.forEach(function(mutation) {
          if (mutation.type === 'childList') {
            var list_values = [].slice.call(list.children)
                .map( function(node) { return node.innerHTML; })
                .filter( function(s) {
                  if (s === '
    ') { return false; } else { return true; } }); console.log(list_values); } }); }); observer.observe(list, { attributes: true, childList: true, characterData: true });

    See: https://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/

    Edit: this answer is quite old, now MutationObserver is supported by all browsers except Opera Mini: http://caniuse.com/#feat=mutationobserver

    Also, here's the direct link the the API on MDN: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

提交回复
热议问题