for(var i =0; i< keys.length;i++){
var k = keys[i];
resultUserName.innerHTML = `
<table class="responsive-table highlight">
<thead>
<tr>
<th>Issued Raised By</th>
<th>Issue For</th>
<th>Issue Logged Time</th>
<th>Issue Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>${userData[k].raisedBy}</td>
<td>${userData[k].issueFor}</td>
<td>${userData[k].issueLoggedDate}</td>
<td>${userData[k].issueDescription}</td>
</tr>
</tbody>
</table>
`;
}
我正在尝试将数据库中的所有数据检索到一个表中,它在我控制台登录时显示所有数据但是当我在页面上显示它时它只显示最后一个条目,任何人都可以指出上面的代码有什么问题。
答案 0 :(得分:2)
您需要在循环外部单独构建标题元素,并将循环中的每个行数据构建为字符串,最后附加到DOM
var innerHtml = '<table class="responsive-table highlight">'+
'<thead>'+
'<tr>'+
'<th>Issued Raised By</th>'+
'<th>Issue For</th>'+
'<th>Issue Logged Time</th>'+
'<th>Issue Description</th>'+
'</tr>'+
'</thead>'+
'<tbody>';
for(var i =0; i< keys.length;i++){
var k = keys[i];
innerHTML += '<tr>'+
'<td>${userData[k].raisedBy}</td>'+
'<td>${userData[k].issueFor}</td>'+
'<td>${userData[k].issueLoggedDate}</td>'+
'<td>${userData[k].issueDescription}</td>'+
'</tr>';
}
resultUserName.innerHtml = innerHTML+"</tbody></table>";
答案 1 :(得分:0)
var resultUserName = document.getElementById('resultUserName');
var tableHeader = '<table><thead><tr><th>Issued Raised By</th><th>Issue For</th><th>Issue Logged Time</th><th>Issue Description</th></tr></thead><tbody>;
var tableFooter = '</tbody></table>'
var tableBody = '';
for(var i =0; i< keys.length;i++){
var k = keys[i];
tableBody = tableBody + '<tr>'+
'<td>${userData[k].raisedBy}</td>'+
'<td>${userData[k].issueFor}</td>'+
'<td>${userData[k].issueLoggedDate}</td>'+
'<td>${userData[k].issueDescription}</td>'+
'</tr>';
}
resultUserName.innerHTML = tableHeader + tableBody + tableFooter;
这应该可以解决您的问题。在for循环中,内部html正在被替换。