我是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()')
我猜这是因为我正在返回一个对象,并试图在表格中显示它,但并不完全确定,因为我对此我不熟悉。
非常感谢任何帮助 感谢
答案 0 :(得分:1)
使用此代码:
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
事件时,您尝试获取{{1} }}}但实际上你得到的elements[i]
是elements[elements.length]
。
undefined