所以我有一些 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
或者也许有一个更简单的方法来做到这一点。谢谢!