How to clone() a element n times?

我的未来我决定 提交于 2019-11-30 03:48:21

问题


I have a dynamic table that I want to attach <col> elements with jQuery.

I have this:

var tds = jQuery("tr > td").length; // count how many tds
jQuery("#colgroup-compare > col").clone() // clone
    .appendTo('#colgroup-compare'); // and append

Obviously this only appends 1 <col>, I want to append (n) numbers. How would I do this?

I have the length, I have the clone ability, now how do I combine it?


回答1:


With a loop :

var $col = $("#colgroup-compare > col");
for(var i = 0; i < n; i++){
    $col.clone().appendTo('#colgroup-compare');
}

You can't use jQuery("#colgroup-compare > col").clone().appendTo('#colgroup-compare'); in your loop because that would append more cols at iterations > 0...

This can be optimized :

var $colgroup = $('#colgroup-compare'); // this saves the colgroup collection to avoid recomputing it later
var $col = $colgroup.children("col"); // this makes the clonable col(s) from the col children of $colgroup
for (var i=n; i-->0;){ // n times (from n-1 to 0)
    $colgroup.append($col.clone()); // append a clone of the col(s)
}

EDIT : to count the th in your first row, you may do this :

var n=$("tr").first().children('th').length;

(this avoid counting on more than one row)

Demonstration




回答2:


If you don't want deep clones, then you can avoid the manual iteration by passing the outerHTML of the element to an arrays join() method resulting in an HTMLString corresponding to n number of elements as shown below:

var elementString = new Array(++n).join($(selector).get(0).outerHTML)

which you can append to any element you wish.


In your case you can do:

var n= $("tr > td").length,
$colgroup = $("#colgroup-compare");
$colgroup.append(new Array(++n).join($colgroup.find("col").get(0).outerHTML));


来源:https://stackoverflow.com/questions/12835582/how-to-clone-a-element-n-times

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