使用 JavaScript 或 jQuery 向表中添加多行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14314325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:16:58  来源:igfitidea点击:

Add multiple rows to table using JavaScript or jQuery

javascriptjquery

提问by ?т?

How can I add multiple rows to a table dynamically using jQuery or JavaScript.

如何使用 jQuery 或 JavaScript 将多行动态添加到表中。

回答by THE ONLY ONE

You can use append() to add single row one after the other :

您可以使用 append() 逐行添加单行:

<table id="add"></table>               
<script type="text/javascript">
    function addRow()
    {
        var str ="";
        for(var i=0;i<20;i++)
        {
            str+="<tr>";
            str+="<td>"+i+"</td>";
            str+="</tr>";
        }
        $('#add').html(str); or $('#add').append(str);
    }
</script>

回答by tjdett

This method will add "x" copies of the given cells to the table.

此方法会将给定单元格的“x”个副本添加到表格中。

function add_rows(target, count, cells) {
  for (var i=0; i < count; i++) {
    var row = $('<tr/>');
    for (var c = 0; c < cells.length; c++) {
      row.append($('<td>'+cells[c]+'</td>'));
    }
    $(target).append(row);
  }
}

See http://jsfiddle.net/arLPY/for a demo.

有关演示,请参阅http://jsfiddle.net/arLPY/

回答by Tushar Cse

get the table element and then create a new row for it and thereafter add cells to the row based on number of columns

获取表格元素,然后为其创建一个新行,然后根据列数向该行添加单元格

        var tableID,numRows,numCells;
        function addRow(tableID,numRows) {

        var table = document.getElementById(tableID);
         var i;
         for( i=0 ; i<numRows ;i++)
         {

         var rowCount = table.rows.length;

       var row = table.insertRow(rowCount);

        var cell1 = row.insertCell(0);
        var element1 = document.createElement("input");
        element1.type = "checkbox";
        element1.name="chkbox[]";
        cell1.appendChild(element1);

        var cell2 = row.insertCell(1);
        cell2.innerHTML = rowCount + 1;

        var cell3 = row.insertCell(2);
        var element2 = document.createElement("input");
        element2.type = "text";
        element2.name = "txtbox[]";
        cell3.appendChild(element2);
          }


    }