使用Firestore的snapshot.forEach创建表

问题描述 投票:-2回答:2

我正在尝试将填充了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代码行的方式吗?

javascript arrays firebase google-cloud-firestore
2个回答
0
投票

您将在循环的每次迭代中重置整个showList元素:

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

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


0
投票

假设这个标记:

<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);
});
© www.soinside.com 2019 - 2024. All rights reserved.