根据jquery中的行数和列数生成表 [英] Generate table based on number of rows, columns in jquery

查看:61
本文介绍了根据jquery中的行数和列数生成表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I generate a table in jQuery based on a given number of rows and columns?

推荐答案

您可以使用嵌套for循环,创建元素并将它们相互附加。这是一个非常简单的示例,演示如何创建DOM元素并附加它们。

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.

您会注意到 $('< tag>' )语法将创建一个元素,您可以使用 appendTo 方法好吧,做到这一点。然后,您可以将结果表添加到DOM。

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

这篇关于根据jquery中的行数和列数生成表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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