有了一个循环:
var $col = $("#colgroup-compare > col");
for(var i = 0; i < n; i++){
$col.clone().appendTo('#colgroup-compare');
}
你不能在你的循环使用jQuery("#colgroup-compare > col").clone().appendTo('#colgroup-compare');
,因为这将在迭代> 0追加更多的cols ...
这可以进行优化:
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)
}
编辑:在您的第一排中计数th
,您可以这样做:
var n=$("tr").first().children('th').length;
(这避免计算上多于一行)
Demonstration
为什么不是循环? –