简体   繁体   English

如何使用香草JavaScript和Firebase将li正确附加到ul?

[英]How to properly append li to ul using vanilla JavaScript and Firebase?

So I do want to get all of my messages in my firebase database console. 因此,我确实想在Firebase数据库控制台中获取所有消息。 My code is plain JavaScript. 我的代码是纯JavaScript。

HTML 的HTML

<ul class="collection" id="chatList"></ul>

JS JS

var databaseRef = firebase.database().ref('messages');
var chatList = document.getElementById('chatList');
databaseRef.on('value', function(snapshot) {
  snapshot.forEach(function(childSnapshot) {
      chatList.appendChild('<li class="collection-repeat">' + childSnapshot.val().message + '</li>');
  })
});

在此处输入图片说明

With my code, I only get the last value in the database because I guess it also appends the other <li> that is being generated inside the foreach. 使用我的代码,我只能得到数据库中的最后一个值,因为我猜它还会附加在foreach内部生成的另一个<li>

What is the proper way to append <li> so that it won't also append the other <li> ? 什么是追加<li>的正确方法,以便它也不会追加其他<li>

I know that in jQuery, it can be achieved like this: 我知道在jQuery中,可以这样实现:

$('#chatList').append('<li class="collection-repeat">' + childSnapshot.val().message + '</li>')

Any help would be much appreciated. 任何帮助将非常感激。

appendChild() is used to append a node to an element. appendChild()用于将node追加到元素。 But you are trying to append a string . 但是您正在尝试附加一个string

Try using 尝试使用

var databaseRef = firebase.database().ref('messages');
var chatList = document.getElementById('chatList');
databaseRef.on('value', function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
        var node = document.createElement("li");
        node.className="collection-repeat";
        var textnode = document.createTextNode( childSnapshot.val().message );
        node.appendChild(textnode);
        chatList.appendChild(node);
    })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM