如何在网页中显示js查询结果

问题描述

查询了我的 firebase 数据库来计算订阅主题的人数。我已经在 console.log() 中收到了结果,我想在 div customerNumber 的网页上显示结果。下面的代码在每个主题旁边显示相同的数字,即使在 console.log() 中的每个主题下都显示了正确的数字。我该如何纠正?

这是我的 HTML 代码

<div class="rh_topic" title="Title" ></div>
<div class="customerNumber"></div>

这是我的 javascript 文件中的代码

    function countSubscribers () {
    const topics = document.querySelectorAll(".rh_topic");
    topics.forEach(topic => {
        let number = topic.title;
        const ref = firebase.database().ref('topics/' + number);
        ref.once("value")
        .then(function(snapshot) {
            console.log(topic.title);
            console.log(snapshot.numChildren());
            let customers = snapshot.numChildren();
            const elements = document.getElementsByClassName('customerNumber');
            Array.prototype.forEach.call(elements,function(element) {
                element.textContent = customers;
            });             
        });
    });
}
            
countSubscribers(); 

解决方法

为了简化,你可以使用

elements.map((elements,indexEl) => {
  elements.innerText = customers
  return true;
})