简体   繁体   中英

Using Firebase to list and sort records from greatest to least and print to HTML table body

I have a list of players and their accumulated winnings in firebase. Each record will be added to the from least to greatest.

<table id="toptenwinners" class="table table-hover table-sm">
<thead>
<tr>
<th>Rank</th>
<th>Player</th>
<th>Earnings</th>
<th>Tokens</th>
</tr>
</thead>
<tbody>
<tr>  <-- start of insert
<th scope="row">1</th>  <-- number generated after sort
<td>John Q Public</td> <-- from "player" in firebase
<td>552,133</td>       <-- from "total earnings" in firebase
<td>1,212,808</td>     <-- from "tokens" in firebase
</tr> <-- end of insert
 ..next record

The routine written doesn't seem to work well for this simple application.

dataRef.on('player',function(toptenwinners){

var toptenwinnersHTML = "";

toptenwinners.forEach(function(firebaseOrderReference){
var toptenwinners = dataRef.val();
console.log(toptenwinners); 
var tableofwinners = 

<tr>
<th scope="row">1</th>  
<td>' + player + '</td> 
<td>' + t_earnings + '</td>       
<td>' + t_token + '</td>     
</tr>;

toptenwinnersHTML = toptenwinnersHTML + tableofwinners;
});

$('#toptentable').html(toptenwinnersHTML);
});

I'm wondering if there is a simpler way (using jquery) to list all the 'players' in the DB, their earnings and tokens cleanly into the . Add a way to sort from highest tokens (t_tokens) to least, then number each "row" (ie 1, 2, 3, 4..) based on the sort.

Sample HTML Output:
Rank Name       Earnings Tokens
1    Spongebob  55,222   1,234,555
2    DarthVadar 88,010   555,213
3    PacMan     12,123   120,111

在此处输入图片说明

Sad how questions go stale around here. Anywho, figured it out. The trick was in using the data.ref().once function to list all the content of the DB then gracefully pass the results (on each iteration) to the html table format.

Worked like a charm..

function listthechamps() {

let y = 0
$("#tableChampion").empty();

var database = firebase.database();
database.ref().once('value', function (snapshot) {
if (snapshot.exists()) {
var content = '';
snapshot.forEach(function (data) {
y++
var val = data.val();
content += '<tr>';
content += '<td>' + y + '</td>';
content += '<td>' + val.player + '</td>';
content += '<td>' + val.t_earnings + '</td>';
content += '<td>' + val.t_token + '</td>';
content += '</tr>';
});
$('#tableChampion').append(content);
}
});
}

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