【发布时间】:2026-01-16 20:35:01
【问题描述】:
所以我有一些 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
或者也许有一个更简单的方法来做到这一点。 谢谢!
【问题讨论】:
-
您也可以在输入元素周围加上标签。里程可能会有所不同:)
-
在克隆中使用类不是更好吗?
-
@popnoodles 可能。但正如我解释的那样,有些东西需要特定的 ID。所以对我来说,这是必须的。谢谢
-
"something requires specific IDs" 所以你不能使用这个选择器:"
#element1 .someinput" "#element2 .someinput" "element3 .someinput" 来专门定位东西?您正在使用 jQuery - 这可能不是必须的。 -
我敢打赌,如果你提供了更多关于你认为你为什么需要这个的信息,我们可能会告诉你为什么你不需要。可以做你想做的事。我非常怀疑这是必要的。
标签: javascript jquery