使用javascript填充HTML表

时间:2014-04-09 17:47:22

标签: javascript jquery html

大家好,提前谢谢。我需要学习如何使用以下结构使用javascript填充表格。

var contacts = [
    {name:"name1", number:"number1", address:"address1", notes:"note1"},
    {name:"name2", number:"number2", address:"address2", notes:"note2"},
    {name:"name3", number:"number3", address:"address3", notes:"note3"},
    {name:"name4", number:"number4", address:"address4", notes:"note4"},
    {name:"name5", number:"number5", address:"address5", notes:"note5"}
]

3 个答案:

答案 0 :(得分:1)

<强> HTML

<table id="tableID">
    <tbody>
    </tbody>
</table>

<强>的Javascript

            var wrap= function(value) {
                return "<td>" + value + "</td>";
            };

            $("#tableID tbody").append("<tr><th>Name</th><th>Number</th><th>Address</th><th>Notes</th></tr>");
            for (var i = 0; i < contacts.length; i += 1) {
                $("#tableID tbody").append("<tr>"+ wrap(contacts[i].name)+ wrap(contacts[i].number)+ wrap(contacts[i].address)+ wrap(contacts[i].notes)+ "</tr>")

            }

答案 1 :(得分:0)

var table = $('<table>');

var c, i, l, tr, td;

for (i = 0, l = contacts.length; i < l; i += 1) {
  c = contacts[i];
  tr = $('<tr>');
  tr
    .append($('<td>' + c.name + '</td>'))
    .append($('<td>' + c.number + '</td>'));
  table.append(tr);
}

答案 2 :(得分:0)

试试这个

HTML

<table>

</table>

Jquery

var output='';
for(var i in contacts)
{
   output+='<tr><td>'+contacts[i].name+'</td><td>'+contacts[i].number+'</td><td>'+contacts[i].address+'</td><td>'+contacts[i].notes+'</td></tr>';
}
$('table').empty().append(output)

DEMO