我正在开发一个连接到Firebase数据库的调查应用程序。作为参考,firebase数据库使用JSON结构。以下是我的数据库片段:
我在我的控制台中显示了正确的孩子(问题),但我只能在我的html标题中显示一次值。虽然我可以在控制台中看到它们,但标题不会循环显示HTML页面上的每个问题。这是我需要你帮助的地方。我不知道如何循环HTML标记来显示数据。我在互联网上搜索了一段时间,但一直未能找到合适的解决方案。以下是我目前的代码:
<!DOCTYPE html>
<html>
<head>
<title>DAILY SURVEY REMINDER</title>
</head>
<body>
<div>
<h id = questions> </h1>
</div>
</body>
<script src="https://www.gstatic.com/firebasejs/4.12.1/firebase.js"> .
</script>
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase-
app.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase-
auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase-
database.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase-
firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase-
messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase-
functions.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyCOUA9eYXRgrStbMXx-bcE2lR7e5IYjP2g",
authDomain: "testingdb-a8cd7.firebaseapp.com",
databaseURL: "https://testingdb-a8cd7.firebaseio.com",
projectId: "testingdb-a8cd7",
storageBucket: "testingdb-a8cd7.appspot.com",
messagingSenderId: "384953133465"
};
firebase.initializeApp(config);
</script>
<script src = "https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
var question = document.getElementById('questions');
window.onload = function getData(){
for( i = 1; i < 35; i++){
var dbRef = firebase.database().ref('Questions/'+i).child('questions');
dbRef.on('value', snap => { question.innerText =
JSON.stringify(snap.val(), null, 3);
console.log(snap.val());
question = snap.val();
});
}
};
</script>
</html>
答案 0 :(得分:1)
如何将逻辑替换为:
const selectedRoles: {[key: string]: boolean} = {};
selectedRolesDB.forEach((value: string) => selectedRoles[value] = true);
请尝试告诉我们。
答案 1 :(得分:0)
每次您当前加载问题时都会使用它运行此代码:
question = snap.val();
这意味着您每次都会使用最新的问题替换questions
元素,这就解释了为什么您最后只能看到最后一个问题。
如果您有问题列表,最好使用包含列表的元素,例如有序列表(<ol>
)。然后,对于每个问题,您都会在该问题中插入一个<li>
。
HMTL元素:
<ol id="questions"> </ol>
然后是代码:
var question = document.getElementById('questions');
var dbRef = firebase.database().ref('Questions');
window.onload = function getData(){
for(i = 1; i < 35; i++) {
dbRef.child(i+'/questions').once('value', snap => {
var li = document.createElement("li");
li.innerText = snap.val();
question.appendChild(li);
});
}
};
如果您想显示所有问题而不是前35个问题,您只需让Firebase为您调用所有子节点:
var question = document.getElementById('questions');
var dbRef = firebase.database().ref('Questions');
window.onload = function getData(){
dbRef.on('child_added', snap => {
var li = document.createElement("li");
li.innerText = snap.val().questions;
question.appendChild(li);
});
};