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

Sort elements after adding new element dynamically

我正在使用 Firebase 作为后端开发排行榜。他们给出了这个教程 - https://www.firebase.com/tutorial/#session/e5u73mr8wvp

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

if (prevScoreName === null) {
      $("#leaderboardTable").append(newScoreRow);
    }
    else {
      var lowerScoreRow = htmlForPath[prevScoreName];
      lowerScoreRow.before(newScoreRow);
    }

用于处理 'score added' 的函数,摘自此代码段 -

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

我建议,要了解更多信息,请查看上面给出的教程link,请逐步解释我之前发布的上述代码片段。

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

每个 child 在 Firebase 上按升序排序,因为这些 children 的优先级等于它们的分数,这就是为什么在代码中, child 没有前一个child 附加到底部。这样做是为了让 table 看起来是按降序排列的,就像排行榜应该的那样。

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

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