微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在网页中显示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;
})

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。