简体   繁体   English

将行和单元格追加到表

[英]Append row and cell to table

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. 任何建议都会有所帮助。

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 演示: 小提琴

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM