多次克隆元素 [英] Cloning an element multiple times
本文介绍了多次克隆元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个li element
与id
holder
一起作为div
的父项.我需要多次克隆li
,将所有克隆作为holder div
的父项,然后更改其data-ids
.我的层次结构如下所示:
I have a li element
parented to a div
with id
holder
. I need to clone the li
multiple times, have all the clones parented to the holder div
and change their data-ids
. My hierarchy looks like this:
<div id="holder">
<li data-id=0 class="element">
//other nodes
</li>
</div>
我该如何克隆li element
,然后将其更改为data-id
,所以我得到了:
How can I clone the li element
and than change it's data-id
so I get:
<div id="holder">
<li data-id=0 class="element">
//other nodes
</li>
<li data-id=1 class="element">
//other nodes
</li>
<li data-id=2 class="element">
//other nodes
</li>
<li data-id=3 class="element">
//other nodes
</li>
<li data-id=4 class="element">
//other nodes
</li>
<li data-id=5 class="element">
//other nodes
</li>
</div>
-大卫
推荐答案
Just use clone
and attr
:
var holder, li, clone, counter;
holder = $("#holder");
li = holder.find("li:first");
counter;
for (counter = 1; counter <= 5; ++counter) {
clone = li.clone();
clone.attr("data-id", counter);
clone.appendTo(holder);
}
这篇关于多次克隆元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文