所以我有一些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