我想要设计一种方法,在添加一个简单的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,标签和输入标签填充(甚至更好)
我在某处读到它很慢,可能在所有浏览器上都不支持。 – Azder 2011-02-06 19:04:32