我有一个日期数组。在加载时我想用Moment JS解析这些日期,然后在myTable的B列中显示这些日期。
到目前为止,我已经将数组的最后一个值返回3次,我不知道为什么。
function loadFunction () {
var cellData = ["2016-08-24 12:45", "2016-08-24 16:00","2016-08-24 13:00"];
var myTable = document.getElementById("myTable");
var times = [];
for (var i =0; i <cellData.length; i++) {
var date = moment(cellData[i]).format('MM/DD/YYYY hh:mm a');
times.push(date);
for (var j=1; j < 6 ; j+=2) {
myTable.rows[j].cells[1].innerHTML = times[i];
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
<body onload="loadFunction()">
<table id="myTable">
<thead>
<tr>
<th colspan="3">Table</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
<tr style="display:none;">
<td colspan="3"></td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
<tr style="display:none;">
<td colspan="3"></td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
<tr style="display:none;">
<td colspan="3"></td>
</tr>
</tbody>
</body>
答案 0 :(得分:0)
您的第二个for
为每个值迭代3次。因此,在单元格的最后一个值,它将设置为单元格1 3和5相同的值。尝试在for之外声明变量,并在迭代之后更改j
function loadFunction () {
var cellData = ["2016-08-24 12:45", "2016-08-24 16:00","2016-08-24 13:00"];
var myTable = document.getElementById("myTable");
var times = [];
var j=1;
for (var i =0; i <cellData.length; i++) {
var date = moment(cellData[i]).format('MM/DD/YYYY hh:mm a');
times.push(date);
myTable.rows[j].cells[1].innerHTML = times[i];
j += 2;
}
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
<body onload="loadFunction()">
<table id="myTable">
<thead>
<tr>
<th colspan="3">Table</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
<tr style="display:none;">
<td colspan="3"></td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
<tr style="display:none;">
<td colspan="3"></td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
<tr style="display:none;">
<td colspan="3"></td>
</tr>
</tbody>
</body>
&#13;