首页 > 解决方案 > 使用 Firebase 从最大到最小列出和排序记录并打印到 HTML 表格正文

问题描述

我有一份玩家名单和他们在火力基地中累积的奖金。每条记录将从最小到最大添加。

<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

编写的例程似乎不适用于这个简单的应用程序。

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

我想知道是否有一种更简单的方法(使用 jquery)将数据库中的所有“玩家”、他们的收入和令牌干净地列出到 . 添加一种从最高标记 (t_tokens) 到最少排序的方法,然后根据排序对每个“行”(即 1、2、3、4..)进行编号。

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

在此处输入图像描述

标签: javascriptjqueryfirebasefirebase-realtime-database

解决方案


可悲的是,这里的问题如何变得陈旧。任何人,想通了。诀窍在于使用 data.ref().once 函数列出数据库的所有内容,然后优雅地将结果(在每次迭代中)传递给 html 表格格式。

像魅力一样工作..

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

推荐阅读