将行和单元格附加到表格

时间:2022-12-29 20:10:32

I have following code:

我有以下代码:

   function createTable() {
        var $table = $('<table>').css({border:'1px dotted lightgrey'});
        var $row = $('<tr>').css({ height: '20px' });
        var $cell = $('<td>').css({width:'120px'});

        $row.append($cell).append($cell);
        $table.append($row).append($row);
        $('body').append($table);
    }

I want to create 2 cell and row inside table but the result is not what I expect, It creates only 1 for each row and cell.

我想在表中创建2个单元格和行,但结果不是我所期望的,它为每个行和单元格创建只有1。

Any advice will be helpful.

任何建议都会有所帮助。

2 个解决方案

#1


1  

You need to clone the cell, else it will be same as relocating the cell when you use .append() second time

您需要克隆单元格,否则它将与第二次使用.append()时重定位单元格相同

$row.append($cell).append($cell.clone());

Demo: Fiddle

#2


0  

In extension to Aruns answer,

在扩展到Aruns的答案,

You can create a method to clone things if you have to add rows or cells multiple times,

如果必须多次添加行或单元格,可以创建克隆内容的方法,

function CreateClone(obj, count) {
    count = count || 1;
    var clones = [];

    for (var i = 0; i < count; i++) {
        clones.push(obj.clone());
    }

   return clones;
}

And call it like this,

并称之为,

var rowClones = CreateClone($('<tr>').css({ height: '20px' }), 5);
var cellClones = CreateClone($('<td>').css({width:'120px'}), 5);

#1


1  

You need to clone the cell, else it will be same as relocating the cell when you use .append() second time

您需要克隆单元格,否则它将与第二次使用.append()时重定位单元格相同

$row.append($cell).append($cell.clone());

Demo: Fiddle

#2


0  

In extension to Aruns answer,

在扩展到Aruns的答案,

You can create a method to clone things if you have to add rows or cells multiple times,

如果必须多次添加行或单元格,可以创建克隆内容的方法,

function CreateClone(obj, count) {
    count = count || 1;
    var clones = [];

    for (var i = 0; i < count; i++) {
        clones.push(obj.clone());
    }

   return clones;
}

And call it like this,

并称之为,

var rowClones = CreateClone($('<tr>').css({ height: '20px' }), 5);
var cellClones = CreateClone($('<td>').css({width:'120px'}), 5);