How to clone() a element n times?

前端 未结 2 1168
渐次进展
渐次进展 2021-01-04 21:10

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

I have this:

var tds = jQuery(\"tr > td\").length; //          


        
2条回答
  •  感动是毒
    2021-01-04 21:18

    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

提交回复
热议问题