在动态表javascript中显示对象数组

时间:2015-03-29 21:57:21

标签: javascript arrays

我想使用javascript在动态表格中显示一个对象数组。

var rows=[{ name : "John", age:20, email: "xx@hotmail.com"},
    { name : "Jack", age:50, email: "xxx@hotmail.com"},
    { name : "Son", age:45, email: "xxxx@hotmail.com"}
........................etc
   ];

这就是它的外观。我想知道如何将其显示为动态表格。

1 个答案:

答案 0 :(得分:9)

您就是这样做的:

Javascript解决方案:

<强> FIDDLE

var rows = [{
    name: "John",
    age: 20,
    email: "xx@hotmail.com"
}, {
    name: "Jack",
    age: 50,
    email: "xxx@hotmail.com"
}, {
    name: "Son",
    age: 45,
    email: "xxxx@hotmail.com"
}];

var html = "<table border='1|1'>";
for (var i = 0; i < rows.length; i++) {
    html+="<tr>";
    html+="<td>"+rows[i].name+"</td>";
    html+="<td>"+rows[i].age+"</td>";
    html+="<td>"+rows[i].email+"</td>";

    html+="</tr>";

}
html+="</table>";
document.getElementById("box").innerHTML = html;

jQuery解决方案:

<强> FIDDLE

var rows = [{
        name: "John",
        age: 20,
        email: "xx@hotmail.com"
    }, {
        name: "Jack",
        age: 50,
        email: "xxx@hotmail.com"
    }, {
        name: "Son",
        age: 45,
        email: "xxxx@hotmail.com"
    }];

$(document).ready(function () {
    var html = "<table border='1|1'>";
    for (var i = 0; i < rows.length; i++) {
        html+="<tr>";
        html+="<td>"+rows[i].name+"</td>";
        html+="<td>"+rows[i].age+"</td>";
        html+="<td>"+rows[i].email+"</td>";

        html+="</tr>";

    }
    html+="</table>";
    $("div").html(html);
});