在Javascript/jQuery中生成表 [英] Generating a table in Javascript/jQuery

查看:74
本文介绍了在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屋!

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