【发布时间】:2021-02-18 13:35:50
【问题描述】:
我有一个 FireBase 实时数据库,其中包含一些我想在 HTML 网格中显示的数据。数据库的结构非常简单:
我想要做的是将“id”、“第一列”、“第二列”、“第三列”作为列标题和来自数据库的数据显示在每个相应的标题下。
这是我的 HTML 部分:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<!--Firebase SDK code below-->
<script src="/__/firebase/8.2.6/firebase-app.js"></script>
<script src="/__/firebase/8.2.6/firebase-analytics.js"></script>
<script src="/__/firebase/8.2.6/firebase-database.js"></script>
<!-- Initialize Firebase -->
<script src="/__/firebase/init.js"></script>
<script src="firebase.js"></script>
<button onClick="readData()">Load data from FB</button>
<table class="table table-striped" id="table">
<thead>
<tr>
<th>ID</th>
<th>First column</th>
<th>Second column</th>
<th>Third column</th>
</tr>
</thead>
<tbody>
</body>
</html>
这里是JS:
// Firebase reference
var database = firebase.database();
rootRef = database.ref('/');
itemsRef = database.ref('/Items/');
// Other vars
var pushLabels = ["id", "First column", "Second column", "Third column"];
function readData() {
itemsRef.once('value', function (snapshot) {
var arrayLen = pushLabels.length;
var childKeyArr = [];
var table = document.querySelector('#table tbody');
snapshot.forEach(function (childSnapshot) {
var childKey = childSnapshot.key;
childKeyArr.push(childKey);
});
for (var i = 0; i < childKeyArr.length; i++) {
var row = table.insertRow(-1);
for (var j = 0; j < arrayLen; j++) {
cell = row.insertCell(-1);
};
};
for (var i = 0; i < childKeyArr.length + 1; i++) {
database.ref('/Items/' + i).once('value', function (snapshot) {
snapshot.forEach(function (childSnapshot) {
var noha = childSnapshot.val();
for (var i = 0; i < pushLabels.length; i++) {
cell.innerHTML = noha;
};
});
});
}
});
}
我认为它相当“过于复杂”。我能够根据数据库中父项的数量(1、2、3,如数据库层次结构屏幕截图所示)创建行,并且对于每个节点,我都能够将数据检索到快照中,但我不知道如何将其投影到网格中,以便每个值正确显示到它的相关列。 我在代码中放入单元格的部分显然是错误的 - 我只是在测试不同的方式。
任何帮助将不胜感激!此外,如果有任何更好的解决方案,一些可以以更简单的方式做到这一点的库,如果你能推荐,我会很高兴。 谢谢!!
【问题讨论】:
标签: javascript html firebase firebase-realtime-database