2011-02-06 73 views
2

我想要设计一种方法,在添加一个简单的div元素时添加一个类和一些数据 - *,它将替换它或者添加到其中其他元素。这个方法不应该手动调用,而是自动地通过某种.live()jQuery方法,自定义事件或类似$('body')。bind('create.custom')等等。 我需要它这种方式,因为我不会提前知道什么元素将被创建,因为他们将通过像单个空div或p的ajax服务。如何捕捉DOM元素的创建并使用jQuery来操作它们

<!DOCTYPE html> 
<html> 
    <head> 

     <title >on create</title> 

     <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" ></script> 

     <script type="text/javascript" > 

      jQuery(function($){ 
       $("div.fancyInput").each(function(index,element){ 

        var $div = $(this); 
        var dataId = $div.attr("data-input-id"); 
        var inputId = ''; 
        var labelId = ''; 
        if(!!dataId){ 
         inputId = 'id="' + dataId + '"'; 
         labelId = 'id="' + dataId + 'Label"'; 
        } // if 

        var dataValue = $div.attr(); 

        $(
         '<p class="fancyInput" >' + 
         ' <label ' + labelId + ' for="' + inputId + '" >A fancy input</label>' + 
         ' <input ' + inputId + ' name="' + inputId + '" value="A fancy input" />' + 
         '</p>' 
        ).appendTo($div);    
       }); // .each() 
      }); // jQuery() 
     </script> 

     <script type="text/javascript" > 

      jQuery(function($){ 
       var counter = 2; 
       var $form = $('#form'); 
       $('#add').click(function(event){ 
        $('<div class="fancyInput" data-input-id="fancyInput' + counter + '" ></div>').appendTo($form); 
        counter++; 
       }); // .click 
      }); // jQuery() 

     </script> 
    </head> 
    <body> 

     <a id="add" href="#" > add another one </a> 
     <form id="form" action="#" > 

      <p class="normalInput" > 
       <label id="normalInputLabel" for="normalInput" >A normal input</label> 
       <input id="normalInput" name="normalInput" value="A normal input" /> 
      </p> 

      <div class="fancyInput" ></div> 

     </form> 
    </body> 
</html> 

更新: 我检查的liveQuery事前,它是一种功能,我需要的,但在执行的事件回调修改DOM元素的能力。因此,我不仅需要附加事件,还需要在创建元素时修改DOM。例如:每创建一个新的应用程序,它都应该被p,标签和输入标签填充(甚至更好)

回答

4

您可以使用DOM级别3事件,如DOMNodeInserted。这可能是这样的:

$(document).bind('DOMNodeInserted', function(event) { 
    // A new node was inserted into the DOM 
    // event.target is a reference to the newly inserted node 
}); 

作为替代方案,您可能检出.liveQueryhelp jQuery插件。

更新

在referrence您的意见,看看http://www.quirksmode.org/dom/events/index.html,只是不支持它是这个这个世界的互联网浏览器的探险家(我猜IE9至少一样)。

我不能说太多的表现,但它应该表现得相当好。

+0

我在某处读到它很慢,可能在所有浏览器上都不支持。 – Azder 2011-02-06 19:04:32

相关问题