所以我有一些HTML我想克隆几次并附加到文档中。这只是典型的HTML表单。但由于像<label for="something">
这样的东西基于元素ID工作,所以如果jquery clone()
'd元素中的每个HTML元素除了它们所有的克隆对象之外都可以具有唯一的ID,那就太好了。就像猜测我如何做到这一点一样,我想知道是否有可能让我的初始元素中的ID都包含一些唯一的字符串。然后,我可以以某种方式遍历元素,并用_1,_2,_3等替换该字符串。替换jquery克隆对象中的html元素的ID号
我还没有走得很远,但它看起来像这样应该工作。
$(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
或者,也许有一个更简单得多的方式来做到这一点。 谢谢!
你也可以在输入元素周围包装一个标签。里程可能会有所不同:) –
在克隆中使用类不是更好吗? – Popnoodles
@ popnoodles大概。但正如我所解释的,有些东西需要特定的ID。所以对我来说,这是必须的。谢谢 – 1252748