多次克隆一个元素
我有一个 li 元素
,其父级为 div
,其 id
holder
。我需要多次克隆 li
,让所有克隆都成为 holder div
的父级,并更改它们的 data-ids
。我的层次结构如下所示:
<div id="holder">
<li data-id=0 class="element">
//other nodes
</li>
</div>
如何克隆 li 元素
并更改它的 data-id
所以我得到:
<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>
-- David
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>
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>
-- David
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需使用
clone
和clone
即可。 jquery.com/attr" rel="nofollow">attr
:Just use
clone
andattr
:这是一个快速而肮脏的解决方案:
http://jsfiddle.net/Epzt9/7/
另外 - 和我很惊讶没有其他人提到这一点 - 列表项的包含元素应该是
,而不是
-
标签不独立存在,它们应该属于一个列表。
Here's a quick and dirty solution:
http://jsfiddle.net/Epzt9/7/
Also - and I'm surprised no-one else has mentioned this - your containing element for the list items should be a
<ul>
, not a<div>
-<li>
tags don't stand on their own, they should belong to a list.按照这些思路应该可以工作:
它获取对
#holder
和 克隆 那个。然后,它将data-id
属性的当前值加 1,并将克隆追加回#holder
。但是,这实际上不会更改元素上属性的值(如果您检查 DOM,克隆似乎与它们来自的元素具有相同的
data-id
值)。新值与该元素关联,如果您稍后使用 jQuerydata
方法获取该值,这很好。如果没有,您需要使用attr
而不是data
来设置该值。Something along these lines should work:
It gets a reference to the last
li
child of#holder
and clones that. It then adds 1 to the current value of thedata-id
attribute, and appends the clone back into#holder
.However, this won't actually change the value of the attribute on the element (if you inspected the DOM, clones would appear to have the same
data-id
value as the element from which they came). The new value is associated with the element, which is fine if you are using the jQuerydata
method to obtain this value later. If not, you would need to useattr
instead ofdata
to set the value.