【问题标题】:How to display user comments dynamically to html?如何将用户评论动态显示到html?
【发布时间】:2021-01-11 20:13:49
【问题描述】:

我正在开发一个网站,它的底部有一个评论部分。我开发了一个“添加评论”按钮,将评论存储到 firebase firestore。但是,我正在努力解决如何在我的网站上显示 cmets。我知道如何从 firestore 获取所有 cmets,但我不知道如何在我的网站上显示它们。我在谷歌上搜索了几个小时,但没有完全找到我想要的,因此感谢您的帮助。

所以,我有一个评论输入和一个提交按钮:

    <input
      type="text"
      class="form-control"
      placeholder="Comment"
      id="comment"
      aria-describedby="basic-addon1"
      />

<button
    type="button"
    class="btn btn-dark"
    data-bs-dismiss="modal"
    onclick="postComment()"
     >
     Comment
</button>

还有一个将其发布到 firebase firestore 的功能:

function postComment() {
  var name = document.getElementById("name").value;
  var comment = document.getElementById("comment").value;

  let db = firebase.firestore();
  db.collection("comments")
    .add({
      name,
      comment,
      time: firebase.firestore.Timestamp.fromDate(new Date()),
    })
    .catch((error) => {
      console.log(error);
    });
}

这就是我从 firestore 获取数据的方式:

db.collection("cities").get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        console.log(doc.id, " => ", doc.data());
    });
});

现在我只想知道一种在我的网站上显示 cmets 的动态方式。换句话说,评论部分的布局/模型。

提前致谢

【问题讨论】:

标签: javascript html css firebase


【解决方案1】:

下面的sn-p代表一个基本思想。如果您有任何疑问,请告诉我。

const comments = [
  {
    name: 'Author 1',
    comment: 'Comment from author 1.'
  },
  {
    name: 'Author 2',
    comment: 'Comment from author 2.'
  }
];

const target = document.getElementById('target');

function displayComments(target, comments) {
  comments.forEach((comment) => {
    const element = document.createElement('span');
    element.classList.add('comment');
    element.innerText = `${comment.name} says: ${comment.comment}`;
    target.appendChild(element);
  });
}

displayComments(target, comments);
.container {
  display: flex;
  flex-direction: column;
}

.comment {
  margin: 10px;
}
&lt;div id='target' class='container'&gt;&lt;/div&gt;

【讨论】:

  • 还有一件事。你能推荐一种方法让最后一个 span 元素在顶部吗?换句话说,最后一条评论在顶部。
  • @NabilTheCoder 是的,只需在将数组传递给显示函数之前使用Array.sort(...) 重新排序您的数组,或者如果它已经订购,请将target.appendChild 更改为target.prepend,以便反向添加项目(或者只是反转数组)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
  • 2013-04-13
  • 1970-01-01
  • 1970-01-01
  • 2012-12-07
  • 2016-02-22
相关资源
最近更新 更多