如何克隆()一个元素n次? [英] How to clone() a element n times?

查看:82
本文介绍了如何克隆()一个元素n次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动态表,希望将<col>元素附加到jQuery.

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

我有这个:

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

很明显,这仅附加1个<col>,我想附加(n)个数字.我该怎么办?

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?

推荐答案

带循环:

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.

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

这可以优化:

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,您可以这样做:

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)

演示

这篇关于如何克隆()一个元素n次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆