1

我有 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>
4

3 回答 3

2

这里的例子

你可以用这种方式做你想做的事:

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);
}
于 2013-09-16T13:05:59.470 回答
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>');
于 2013-09-16T12:59:32.807 回答
0

在每个新数组上,你应该创建一个新的 TR 元素请看下面的例子

于 2013-09-16T12:59:30.460 回答