在Javascript/jQuery中生成表 [英] Generating a table in Javascript/jQuery
问题描述
可能重复:
在jQuery中动态创建表
Possible Duplicate:
Creating tables dynamically in jQuery
我有两个数组letters = [A,B,C,...]
和numbers = [1,2,3,...]
,并且想生成一个以numbers
作为标题并且以letters
作为第一个条目的html表(然后我可以用我有). 通用数组有可能吗?
I have two Arrays, letters = [A,B,C,...]
and numbers = [1,2,3,...]
, and would like to generate a html table with numbers
as the headers and letters
as the first entry (and then I can fill it in with values which I have). Is this possible for general Arrays?
即,如下所示:
<table>
<thead>
<tr>
<th></th>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
</thead>
<tbody>
<tr id="A">
<td>A</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr id="B">
<td>B</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr id="C">
<td>C</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
推荐答案
好的,这是我想到的第一种方法:
OK, here's the first way that came to mind:
var letters = ["A","B","C"],
numbers = [1,2,3],
$table = $("<table/>"),
$body = $("<tbody/>").appendTo($table),
$row = $("<tr><th></th></tr>");
$.each(numbers,function(i,val){
$("<th/>").text(val).appendTo($row);
});
$("<thead/>").append($row).appendTo($table);
$.each(letters, function(i,val) {
$row = $("<tr/>").attr("id",val).appendTo($body);
$("<td/>").text(val).appendTo($row);
for (var j = 0; j < numbers.length; j++)
$row.append("<td/");
});
$table.appendTo("body");
演示: http://jsbin.com/ocomit/edit#javascript,html,直播
是的,它可能更漂亮和/或更有效.该方法仅使用非常基本的jQuery方法-如果您不确定其中的任何一种方法,则您知道查看位置. ..
Yes it could be prettier and/or more efficient. This uses only very rudimentary jQuery methods - if you're not sure about any of them you know where to look...
这篇关于在Javascript/jQuery中生成表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!