所以我有一些HTML,我想多次克隆并附加到文档中。它只是典型的HTML表单。但是由于像<label for="something">
之类的东西基于元素ID工作,所以如果jquery clone()
'd元素中的每个HTML元素除了所有克隆的对应元素之外都可以具有唯一ID,那将是很好的。就像我如何做到这一点一样,我想知道是否有可能使我的初始元素中的ID都包含一些唯一的字符串。然后我可以以某种方式遍历元素并用_1,_2,_3等替换该字符串
我没有走得太远,但似乎这样的事情应该有效。
$(document).ready(function(){
var toReplace = "containerUniqueCharacterString1234";
var copy = $('#containerUniqueCharacterString1234').clone(true);
copy[0].style.display = "block"; //so i can reference the first element like this
console.log(copy[0]); //[object HTMLDivElement]
$('body').append(copy);
$.each(copy, function(index, value){
var children = copy[index].childNodes;
console.log(children); //[object NodeList]
var len = children.length;
if (copy[index].childNodes.length > 0){
if (copy[index].childNodes.hasOwnProperty('id')){
//replace the toReplace string with an incremented number here(?)
//annnnd this is where i've gotten in too deep and made this overly complex
}
}
$('#otherResults').append(len);
});
});
http://jsbin.com/ecojub/1/edit
或许有一种更简单的方法可以做到这一点。 谢谢!
答案 0 :(得分:1)
如果要复制HTML元素多次仅用于显示,可能应该考虑使用模板引擎而不是复制DOM元素,这些元素价格昂贵且维护性较差。下划线有一个非常好用的功能,http://documentcloud.github.com/underscore/#template