简体   繁体   中英

Displaying retrieved information from firebase database in an HTML table

I am new to Firebase and trying to retrieve static information from my Firebase Database to display in a table format in HTML

The HTML code I have is:

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

And the JavaScript is

    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);
        });            
    } 

But I am getting the error of:

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

I'm guessing it's because I am returning an object and trying to display that in the table but not entirely sure as I'm new to this as I say.

Any help would be greatly appreciated Thanks

Use this code:

 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);
 });

At the end of for loop variable i is equal elements.length , and when value event is triggered at ref you try to get elements[i] element but actualy you get elements[elements.length] which is 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);
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM