使用 Firestore 的 snapshot.forEach 创建表



我试图将一个充满Firestore对象的数组输出到表中,但只显示表上方的最后一个对象

<table class="darkTable">
<thead>
<tr>
<th>List of Available Shows</th>
</tr>
</thead>
<tbody>
<tr>
<div id="showList"></div>
</tr>
</tbody>
</table>
<script>
firebase.firestore().collection('TV Shows').get().then(snapshot => {
var i = 0;
var array = [];
snapshot.forEach(doc => {
array[i] = doc.data().show.name;
//console.log(doc.data().show.name);
//showList.innerHTML = array[i] + "<br />"; 
showList.innerHTML = '<td>' + array[i] + '</td>';
i++;
});
}); 
</script>

这是我处理td代码行的方式吗?

假设此标记:

<div id="showList"></div>

然后它的工作原理是这样的:

firebase.firestore().collection('TV Shows').get().then(snapshot => {
var showList = document.getElementById('showList');
var html = '<table class="darkTable"><thead><tr>';
html += '<th>List of Available Shows</th>';
/* add further columns into here, alike the one above. */
html += '</tr></thead><tbody>';
snapshot.forEach(doc => {
html += '<tr>';
html += '<td>' + doc.data().show.name + '</td>';
/* add further columns into here, alike the one above. */
html += '</tr>';
});
html += '</tbody></table>';
showList.append(html);
});

循环的每次迭代都会重置整个showList元素:

showList.innerHTML = '<td>' + array[i] + '</td>';

我怀疑你的意思是每次都附加它,或者每次都完全重置它。也许可以尝试在每次迭代中构建一个字符串,然后在循环结束后设置整个字符串。

最新更新