且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Javascript/jQuery中生成表

更新时间:2022-06-01 03:10:56

好的,这是我想到的第一种方法:

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...