简体   繁体   中英

Generate table based on number of rows, columns in jquery

如何根据给定的行数和列数在jQuery中生成表?

You can use nested for loops, create elements and append them to one another. Here's a very simple example that demonstrates creating DOM elements, and appending them.

You'll notice that the $('<tag>') syntax will create an element, and you can use the appendTo method to, well, do exactly that. Then, you can add the resulting table to the DOM.

var rows = 5; //here's your number of rows and columns
var cols = 5;
var table = $('<table><tbody>');
for(var r = 0; r < rows; r++)
{
    var tr = $('<tr>');
    for (var c = 0; c < cols; c++)
        $('<td>some value</td>').appendTo(tr); //fill in your cells with something meaningful here
    tr.appendTo(table);
}

table.appendTo('body'); //Add your resulting table to the DOM, I'm using the body tag for example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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