Javascript 动态添加新元素后对元素进行排序

Javascript 动态添加新元素后对元素进行排序,javascript,jquery,firebase,leaderboard,Javascript,Jquery,Firebase,Leaderboard,我正在使用Firebase作为后端制作排行榜。他们给出了本教程- 我需要帮助解释以下代码行以及它如何保持元素排序 if (prevScoreName === null) { $("#leaderboardTable").append(newScoreRow); } else { var lowerScoreRow = htmlForPath[prevScoreName]; lowerScoreRow.before(newScoreRow);

我正在使用Firebase作为后端制作排行榜。他们给出了本教程-

我需要帮助解释以下代码行以及它如何保持元素排序

if (prevScoreName === null) {
      $("#leaderboardTable").append(newScoreRow);
    }
    else {
      var lowerScoreRow = htmlForPath[prevScoreName];
      lowerScoreRow.before(newScoreRow);
    }
用于处理“添加分数”的函数,此代码段取自-

function handleScoreAdded(scoreSnapshot, prevScoreName) {
    var newScoreRow = $("<tr/>");
    newScoreRow.append($("<td/>").append($("<em/>").text(scoreSnapshot.val().name)));
    newScoreRow.append($("<td/>").text(scoreSnapshot.val().score));

    // Store a reference to the table row so we can get it again later.
    htmlForPath[scoreSnapshot.key()] = newScoreRow;

    // Insert the new score in the appropriate place in the table.
    if (prevScoreName === null) {
      $("#leaderboardTable").append(newScoreRow);
    }
    else {
      var lowerScoreRow = htmlForPath[prevScoreName];
      lowerScoreRow.before(newScoreRow);
    }
  }
函数handleScoreAdded(scoreSnapshot,prevScoreName){
var newScoreRow=$(“”);
newScoreRow.append($(“”).append($(“”).text(scoreSnapshot.val().name));
newScoreRow.append($(“”).text(scoresnashot.val().score));
//存储对表行的引用,以便我们以后可以再次获取它。
htmlForPath[scoreSnapshot.key()]=newScoreRow;
//在表中的适当位置插入新分数。
如果(prevScoreName==null){
$(“#排行榜表格”).append(newScoreRow);
}
否则{
var lowerScoreRow=htmlForPath[prevScoreName];
lowerScoreRow.before(newScoreRow);
}
}

关于更多信息,我建议您查看上面给出的教程链接,并请逐步解释我在此之前发布的上述代码片段。

子添加、更改和移动回调将传递第二个参数,其中包含前一个子项的键。这就是代码对元素进行排序的方式

每个子项在Firebase上按升序排序,因为这些子项的优先级等于它们的分数,这就是为什么在代码中,没有先前子项的子项被追加到底部。这样做是为了使表格看起来像排行榜一样按降序排序

这里有一些更好的评论来解释发生了什么

if (prevScoreName === null) {
  // This child has no child before it, which means it has the lowest score.
  // Append it to the bottom of the table.
  $("#leaderboardTable").append(newScoreRow);
}
else {
  // This child has a child before it with a lower score. Find that previous
  // child in the DOM so we can insert the new child above it.
  var lowerScoreRow = htmlForPath[prevScoreName];
  lowerScoreRow.before(newScoreRow);
}

HtmlFormath是一个数组,对吗?因此,在代码中的一个位置传递一个密钥,在另一个位置传递一个快照。为什么会这样?是的,它是一个数组,子元素的键作为键,
元素作为值。未传入快照。