【问题标题】:Sort elements after adding new element dynamically动态添加新元素后对元素进行排序
【发布时间】:2015-12-12 06:21:57
【问题描述】:

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

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

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

处理'score added'的函数,从这里获取这个sn-p -

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

我建议,要了解更多信息,您可以查看上面给出的教程链接,并请逐步解释我在此之前发布的上述代码 sn-p。

【问题讨论】:

    标签: javascript jquery firebase leaderboard


    【解决方案1】:

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

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

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

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

    【讨论】:

    • htmlForPath 是一个数组对吗?因此,在代码的一个地方传递了一个键,而在另一个地方传递了一个快照。这是为什么呢?
    • 是的,它是一个以孩子的键为键,&lt;tr&gt; 元素为值的数组。未传入快照。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 2011-10-29
    • 1970-01-01
    • 2013-06-10
    • 2014-09-10
    • 1970-01-01
    相关资源
    最近更新 更多