Json数据到表javaScript而不使用jQuery

时间:2013-09-16 12:34:48

标签: javascript json

我有Json数据

var schedule = [
{ date: "Monday, 9:00am", team1: "Chasing", team1Score: "13", team2: "Amsterdam Money Gang", team2Score: "9"},
{ date: "Monday, 9:00am", team1: "Boomsquad", team1Score: "15", team2: "Beast Amsterdam", team2Score: "11"},
];

现在我需要将它添加到下表中,只使用javaScript(所以没有Jquery ,但我们可以使用微库)

 <tr>
     <td data-bind="date"></td>
     <td data-bind="team1"></td>
     <td data-bind="team1score"></td>
     <td data-bind="team2"></td>
     <td data-bind="team2score"></td>
 </tr> 

我使用以下内容循环遍历数组,只是现在我不知道如何在每个数组行上创建一个新的tr

var len = schedule.length; 

for (var i=0; i < len; i++) {

}

所以我试图获得以下输出

                <tr>
                    <td>Monday, 9:00am</td>
                    <td class="winner">Chasing</td>
                    <td>13 - 9</td>
                    <td>Amsterdam Money Gang</td>
                </tr>

                <tr>
                    <td>Monday, 9:00am</td>
                    <td class="winner">Boomsquad</td>
                    <td>15 - 11</td>
                    <td>Beast Amsterdam</td>
                </tr>

3 个答案:

答案 0 :(得分:2)

Example here

你可以这样做你想做的事情:

var len = schedule.length;
var table = document.getElementById('table1');

for (var i=0; i < len; i++) {
    var tr = document.createElement('tr');
    var s = schedule[i];

    var td = document.createElement('td');
    td.innerHTML = s.date;
    tr.appendChild(td);

    td = document.createElement('td');
    td.innerHTML = s.team1;
    tr.appendChild(td);

    td = document.createElement('td');
    td.innerHTML = s.team1Score;
    tr.appendChild(td);

    td = document.createElement('td');
    td.innerHTML = s.team2;
    tr.appendChild(td);

    td = document.createElement('td');
    td.innerHTML = s.team2Score;
    tr.appendChild(td);

    table.appendChild(tr);
}

答案 1 :(得分:1)

尝试此操作,您可能需要根据HTML布局进行调整。

var schedule = [
{ date: "Monday, 9:00am", team1: "Chasing", team1Score: "13", team2: "Amsterdam Money     Gang", team2Score: "9"},
{ date: "Monday, 9:00am", team1: "Boomsquad", team1Score: "15", team2: "Beast Amsterdam", team2Score: "11"},
];

document.write('<table>');
for(var i = 0; i < schedule.length; i++)
{
    var obj = schedule[i];

    document.write('<tr><td>' + obj.date + '</td><td class="winner">' + obj.team1 + '</td><td>' + obj.team1Score + ' - ' + obj.team2Score + '</td><td>' + obj.team2 + '</td></tr>');
}
document.write('</table>');

答案 2 :(得分:0)

在每个新数组上,您应该创建一个新的TR元素 请查看以下example