Pergunta

Quero executar uma função quando alguma div ou entrada for adicionada ao html.Isso é possível?

Por exemplo, uma entrada de texto é adicionada e a função deve ser chamada.

Foi útil?

Solução

Atualização de 2015, novo MutationObserver é compatível com navegadores modernos:

Chrome 18+, Firefox 14+, IE 11+, Safari 6+

Se precisar apoiar os mais velhos, você pode tentar recorrer a outras abordagens como as mencionadas neste artigo. 5 (!) Resposta de um ano abaixo.Existem dragões.Aproveitar :)


Alguém mais está alterando o documento?Porque se você tiver controle total sobre as alterações, você só precisa criar as suas próprias domChanged API - com uma função ou evento personalizado - e acione/chame-a sempre que você modificar coisas.

O DOM Nível 2 tem Tipos de eventos de mutação, mas a versão mais antiga do IE não oferece suporte.Observe que os eventos de mutação são obsoleto na especificação de eventos DOM3 e ter um penalidade de desempenho.

Você pode tentar emular o evento de mutação com onpropertychange no IE (e volte para a abordagem de força bruta se nenhuma delas estiver disponível).

Para completo domChange um intervalo pode ser um exagero.Imagine que você precisa armazenar o estado atual de todo o documento e examinar todas as propriedades de cada elemento para serem iguais.

Talvez se você estiver interessado apenas nos elementos e em sua ordem (como você mencionou na sua pergunta), um getElementsByTagName("*") pode trabalhar.Isto será acionado automaticamente se você adicionar um elemento, remover um elemento, substituir elementos ou alterar a estrutura do documento.

Eu escrevi uma prova de conceito:

(function (window) {
    var last = +new Date();
    var delay = 100; // default delay

    // Manage event queue
    var stack = [];

    function callback() {
        var now = +new Date();
        if (now - last > delay) {
            for (var i = 0; i < stack.length; i++) {
                stack[i]();
            }
            last = now;
        }
    }

    // Public interface
    var onDomChange = function (fn, newdelay) {
        if (newdelay) delay = newdelay;
        stack.push(fn);
    };

    // Naive approach for compatibility
    function naive() {

        var last = document.getElementsByTagName('*');
        var lastlen = last.length;
        var timer = setTimeout(function check() {

            // get current state of the document
            var current = document.getElementsByTagName('*');
            var len = current.length;

            // if the length is different
            // it's fairly obvious
            if (len != lastlen) {
                // just make sure the loop finishes early
                last = [];
            }

            // go check every element in order
            for (var i = 0; i < len; i++) {
                if (current[i] !== last[i]) {
                    callback();
                    last = current;
                    lastlen = len;
                    break;
                }
            }

            // over, and over, and over again
            setTimeout(check, delay);

        }, delay);
    }

    //
    //  Check for mutation events support
    //

    var support = {};

    var el = document.documentElement;
    var remain = 3;

    // callback for the tests
    function decide() {
        if (support.DOMNodeInserted) {
            window.addEventListener("DOMContentLoaded", function () {
                if (support.DOMSubtreeModified) { // for FF 3+, Chrome
                    el.addEventListener('DOMSubtreeModified', callback, false);
                } else { // for FF 2, Safari, Opera 9.6+
                    el.addEventListener('DOMNodeInserted', callback, false);
                    el.addEventListener('DOMNodeRemoved', callback, false);
                }
            }, false);
        } else if (document.onpropertychange) { // for IE 5.5+
            document.onpropertychange = callback;
        } else { // fallback
            naive();
        }
    }

    // checks a particular event
    function test(event) {
        el.addEventListener(event, function fn() {
            support[event] = true;
            el.removeEventListener(event, fn, false);
            if (--remain === 0) decide();
        }, false);
    }

    // attach test events
    if (window.addEventListener) {
        test('DOMSubtreeModified');
        test('DOMNodeInserted');
        test('DOMNodeRemoved');
    } else {
        decide();
    }

    // do the dummy test
    var dummy = document.createElement("div");
    el.appendChild(dummy);
    el.removeChild(dummy);

    // expose
    window.onDomChange = onDomChange;
})(window);

Uso:

onDomChange(function(){ 
    alert("The Times They Are a-Changin'");
});

Isso funciona no IE 5.5+, FF 2+, Chrome, Safari 3+ e Opera 9.6+

Outras dicas

Esta é a abordagem definitiva até agora, com o menor código:

IE9+, FF, Webkit:

Usando Observador de mutação e voltando ao obsoletoEventos de mutação se necessário:
(Exemplo abaixo apenas para alterações de DOM relativas a nós anexados ou removidos)

var observeDOM = (function(){
  var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

  return function( obj, callback ){
    if( !obj || obj.nodeType !== 1 ) return; // validation

    if( MutationObserver ){
      // define a new observer
      var obs = new MutationObserver(function(mutations, observer){
          callback(mutations);
      })
      // have the observer observe foo for changes in children
      obs.observe( obj, { childList:true, subtree:true });
    }
    
    else if( window.addEventListener ){
      obj.addEventListener('DOMNodeInserted', callback, false);
      obj.addEventListener('DOMNodeRemoved', callback, false);
    }
  }
})();

//------------< DEMO BELOW >----------------
// add item
var itemHTML = "<li><button>list item (click to delete)</button></li>",
    listElm = document.querySelector('ol');

document.querySelector('body > button').onclick = function(e){
  listElm.insertAdjacentHTML("beforeend", itemHTML);
}

// delete item
listElm.onclick = function(e){
  if( e.target.nodeName == "BUTTON" )
    e.target.parentNode.parentNode.removeChild(e.target.parentNode);
}
    
// Observe a specific DOM element:
observeDOM( listElm, function(m){ 
   var addedNodes = [], removedNodes = [];

   m.forEach(record => record.addedNodes.length & addedNodes.push(...record.addedNodes))
   
   m.forEach(record => record.removedNodes.length & removedNodes.push(...record.removedNodes))

  console.clear();
  console.log('Added:', addedNodes, 'Removed:', removedNodes);
});


// Insert 3 DOM nodes at once after 3 seconds
setTimeout(function(){
   listElm.removeChild(listElm.lastElementChild);
   listElm.insertAdjacentHTML("beforeend", Array(4).join(itemHTML));
}, 3000);
<button>Add Item</button>
<ol>
  <li><button>list item (click to delete)</button></li>
  <li><button>list item (click to delete)</button></li>
  <li><button>list item (click to delete)</button></li>
  <li><button>list item (click to delete)</button></li>
  <li><em>&hellip;More will be added after 3 seconds&hellip;</em></li>
</ol>

Recentemente escrevi um plugin que faz exatamente isso - jquery.initialize

Você usa da mesma forma que .each função

$(".some-element").initialize( function(){
    $(this).css("color", "blue"); 
});

A diferença de .each é - é preciso o seu seletor, neste caso .some-element e aguarde novos elementos com este seletor no futuro, caso tal elemento seja adicionado, ele também será inicializado.

No nosso caso, a função de inicialização apenas altera a cor do elemento para azul.Então, se adicionarmos um novo elemento (não importa se com ajax ou mesmo com o inspetor F12 ou qualquer coisa), como:

$("<div/>").addClass('some-element').appendTo("body"); //new element will have blue color!

O plugin irá iniciá-lo instantaneamente.Além disso, o plugin garante que um elemento seja inicializado apenas uma vez.Então, se você adicionar elemento, então .detach() do corpo e depois adicioná-lo novamente, ele não será inicializado novamente.

$("<div/>").addClass('some-element').appendTo("body").detach()
    .appendTo(".some-container");
//initialized only once

O plug-in é baseado em MutationObserver - funcionará no IE9 e 10 com dependências conforme detalhado no página leia-me.

ou você pode simplesmente Crie seu próprio evento, que correm por toda parte

 $("body").on("domChanged", function () {
                //dom is changed 
            });


 $(".button").click(function () {

          //do some change
          $("button").append("<span>i am the new change</span>");

          //fire event
          $("body").trigger("domChanged");

        });

Exemplo completohttp://jsfiddle.net/hbmaam/Mq7NX/

O exemplo a seguir foi adaptado do Mozilla Hacks' postagem no blog e está usando Observador de mutação.

// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type == 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();

Suporte ao navegador:Chrome 18+, Firefox 14+, IE 11+, Safari 6+

Use o Observador de mutação interface conforme mostrado no livro de Gabriele Romanato blog

Chrome 18+, Firefox 14+, IE 11+, Safari 6+

// The node to be monitored
var target = $( "#content" )[0];

// Create an observer instance
var observer = new MutationObserver(function( mutations ) {
  mutations.forEach(function( mutation ) {
    var newNodes = mutation.addedNodes; // DOM NodeList
    if( newNodes !== null ) { // If there are new nodes added
        var $nodes = $( newNodes ); // jQuery set
        $nodes.each(function() {
            var $node = $( this );
            if( $node.hasClass( "message" ) ) {
                // do something
            }
        });
    }
  });    
});

// Configuration of the observer:
var config = { 
    attributes: true, 
    childList: true, 
    characterData: true 
};

// Pass in the target node, as well as the observer options
observer.observe(target, config);

// Later, you can stop observing
observer.disconnect();

Que tal estender um jquery para isso?

   (function () {
        var ev = new $.Event('remove'),
            orig = $.fn.remove;
        var evap = new $.Event('append'),
           origap = $.fn.append;
        $.fn.remove = function () {
            $(this).trigger(ev);
            return orig.apply(this, arguments);
        }
        $.fn.append = function () {
            $(this).trigger(evap);
            return origap.apply(this, arguments);
        }
    })();
    $(document).on('append', function (e) { /*write your logic here*/ });
    $(document).on('remove', function (e) { /*write your logic here*/ ) });

O Jquery 1.9+ criou suporte para isso (ouvi dizer que não foi testado).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top