gpt4 book ai didi

javascript - 在 HTML 表中显示从 firebase 数据库检索到的信息

转载 作者:搜寻专家 更新时间:2023-10-30 23:40:14 25 4
gpt4 key购买 nike

我是 Firebase 的新手,正在尝试从我的 Firebase 数据库中检索静态信息以在 HTML 中以表格格式显示

我的 HTML 代码是:

<section>
<table>
<tr>
<th>Number scenario card</th>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
</table>
</section>

JavaScript 是

    var elements = document.getElementsByTagName('td');
// Loop through each tag and place a card in HTML
for(var i = 0; i < elements.length; i++){
// Generate a random number
var rndWCard = "/card" + Math.floor((Math.random() * 6) + 1);
// Get a database reference to our cards with random number appended to end of path
var ref = new Firebase("https://&&**((.firebaseio.com/whiteCards" + rndWCard);
// Attach an asynchronous callback to read the card data from database
ref.on("value", function(snapshot) {
// Print to console for development purposes
console.log(snapshot.val());
// Assign card to each element in the table
elements[i].innerHTML = snapshot.val();
},
function (errorObject) { // Deal with errors
console.log("The read failed: " + errorObject.code);
});
}

但是我得到的错误是:

TypeError: undefined is not an object (evaluating 'elements[i].innerHTML = snapshot.val()')

我猜这是因为我正在返回一个对象并尝试将其显示在表格中,但并不完全确定,因为正如我所说的,我是新手。

任何帮助将不胜感激谢谢

最佳答案

使用这段代码:

 ref.on("value", function(element) {
return function (snapshot) {
console.log(snapshot.val());
element.innerHTML = snapshot.val();
}
}(elements[i]),
function (errorObject) { // Deal with errors
console.log("The read failed: " + errorObject.code);
});

for循环结束时变量i等于elements.length,当value事件为在 ref 处触发 你尝试获取 elements[i] 元素但实际上你得到 elements[elements.length] 这是 undefined.

 ref.on("value", function(element) {
return function (snapshot) {
element.innerHTML = snapshot.val();
console.log(element);
}
}(elements[i]),
function (errorObject) { // Deal with errors
console.log("The read failed: " + errorObject.code);
});

关于javascript - 在 HTML 表中显示从 firebase 数据库检索到的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35816979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com