在HTML表中显示来自firebase数据库的检索信息

时间:2016-03-05 16:57:39

标签: javascript html database html5 firebase

我是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()')

我猜这是因为我正在返回一个对象,并试图在表格中显示它,但并不完全确定,因为我对此我不熟悉。

非常感谢任何帮助 感谢

1 个答案:

答案 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