Cloning an element multiple times

大城市里の小女人 提交于 2019-12-14 02:28:56

问题


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


回答1:


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);
}



回答2:


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.




回答3:


Something along these lines should work:

var clone = $("#holder > li").last().clone();
clone.data("id", parseInt(clone.data("id"), 10) + 1);
$("#holder").append(clone);

It gets a reference to the last li child of #holder and clones that. It then adds 1 to the current value of the data-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 jQuery data method to obtain this value later. If not, you would need to use attr instead of data to set the value.



来源:https://stackoverflow.com/questions/9126873/cloning-an-element-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!