创建一个基本的 HTML/Javascript 排行榜

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47918195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:42:04  来源:igfitidea点击:

Creating a basic HTML/Javascript Leaderboard

javascriptjqueryhtmlcssleaderboard

提问by SteveyG

Whether or not it's easily possible and done with Javascript I'm not sure but..

是否可以轻松实现并使用 Javascript 完成我不确定但是..

As shown in the code below, I've 5 players, each with a different score. I'm looking to code it so that it will automatically relist the players based off how high their score is. IDEALLY, I would also want to colour the first 3 rows to be gold-silver-bronze if that was possible.

如下面的代码所示,我有 5 个玩家,每个玩家都有不同的分数。我希望对其进行编码,以便它会根据他们的得分高低自动重新列出玩家。理想情况下,如果可能的话,我还想将前 3 行着色为金-银-青铜色。

Any help making this or pointing me in the right direction would be much appreciated. I'm not sure where I should start.

任何帮助做到这一点或将我指向正确的方向将不胜感激。我不确定我应该从哪里开始。

#container {
 width: 600px;
 height: auto;
}

.row {
 position: relative;
 display: block;
 width: 100%;
 height: 40px;
 border-bottom: 1px solid #AFAFAF;
}

.name {
 position: relative;
 display: inline-block;
 width: 75%;
 line-height: 45px;
}

.score {
 position: relative;
 display: inline-block;
 width: 25%;
}
<div id="container">
    <div class="row">
        <div class="name">Player1</div><div class="score">430</div>
    </div>
    
    <div class="row">
        <div class="name">Player2</div><div class="score">580</div>
    </div>
    
    <div class="row">
        <div class="name">Player3</div><div class="score">310</div>
    </div>
    
    <div class="row">
        <div class="name">Player4</div><div class="score">640</div>
    </div>
    
    <div class="row">
        <div class="name">Player5</div><div class="score">495</div>
    </div>
</div>

回答by Get Off My Lawn

You can make the first 3 rows the color you want by using nth-child()

您可以使用nth-child()使前 3 行成为您想要的颜色

/* Gold */
.row:nth-child(1) {background: gold;}
/* Silver */
.row:nth-child(2) {background: #c0c0c0;}
/* Bronze */
.row:nth-child(3) {background: #cd7f32;}

Next to sort the items you can put the rows into an array, then use sortto sort the items.

接下来对项目进行排序,您可以将行放入数组中,然后使用sort对项目进行排序。

document.addEventListener('DOMContentLoaded', () => {
  let elements = []
  let container = document.querySelector('#container')
  // Add each row to the array
  container.querySelectorAll('.row').forEach(el => elements.push(el))
  // Clear the container
  container.innerHTML = ''
  // Sort the array from highest to lowest
  elements.sort((a, b) => b.querySelector('.score').textContent - a.querySelector('.score').textContent)
  // Put the elements back into the container
  elements.forEach(e => container.appendChild(e))
})
#container {
  width: 600px;
  height: auto;
}

.row {
  position: relative;
  display: block;
  width: 100%;
  height: 40px;
  border-bottom: 1px solid #AFAFAF;
}

.name {
  position: relative;
  display: inline-block;
  width: 75%;
  line-height: 45px;
}

.score {
  position: relative;
  display: inline-block;
  width: 25%;
}

.row:nth-child(1) {
  background: gold;
}

.row:nth-child(2) {
  background: #c0c0c0;
}

.row:nth-child(3) {
  background: #cd7f32;
}
<div id="container">
  <div class="row">
    <div class="name">Player1</div><div class="score">430</div>
  </div>

  <div class="row">
    <div class="name">Player2</div><div class="score">580</div>
  </div>

  <div class="row">
    <div class="name">Player3</div><div class="score">310</div>
  </div>

  <div class="row">
    <div class="name">Player4</div><div class="score">640</div>
  </div>

  <div class="row">
    <div class="name">Player5</div><div class="score">495</div>
  </div>
</div>

回答by prashant gedam

you can use the highlight class for coloring your rows, here is the fiddle

您可以使用 highlight 类为行着色,这是小提琴

http://jsfiddle.net/fgybyem2/15/

http://jsfiddle.net/fgybyem2/15/

var $divs = $("div.row");
$(document).ready(function () {
    var numericallyOrderedDivs = $divs.sort(function (a, b) {
        return $(a).find(".score").text() > $(b).find(".score").text();
    });
    $("#container").html(numericallyOrderedDivs);    

   $("#container").find(".row:eq(0)").addClass("highLight");
   $("#container").find(".row:eq(1)").addClass("highLight") 
   $("#container").find(".row:eq(2)").addClass("highLight");



});

回答by Jim

I do believe you will have a much more pleasant time here if you represent your data structure with Javascript rather than HTML. What you are describing to me sounds like a collection of data, and in this case I'd make it a Javascript array of objects.

我相信如果你用 Javascript 而不是 HTML 来表示你的数据结构,你会在这里度过更愉快的时光。您向我描述的内容听起来像是一组数据,在这种情况下,我会将其设为 Javascript 对象数组。

const playerArray = [
  {name: "Player1", score: "430", id:"player1"},
  {name: "Player2", score: "580"}, id:"player2"},
  {name: "Player3", score: "310"}, id:"player3"},
  {name: "Player4", score: "640" id:"player4"},
  {name: "Player5", score: "495", id:"player5"}
]

Then sorting this array based on the "score property of the objects is a bit tricky, but with the help of this stack overflow answerI'd say you can write it like this:

然后根据对象的“score 属性对这个数组进行排序有点棘手,但是在这个堆栈溢出答案的帮助下,我会说你可以这样写:

function compare(a,b) {
  if (a.score < b.score)
    return -1;
  if (a.score > b.score)
    return 1;
  return 0;
}

playerArray.sort(compare);

You would then call this sort method each time a player joined , left, submitted a score, etc (anything that modifies the playerArray).

然后,每次玩家加入、离开、提交分数等(任何修改 playerArray 的内容)时,您都会调用此排序方法。

You could then remove all gold, silver, bronze styling from all the rows and then add add the gold color with

然后,您可以从所有行中删除所有金色、银色、青铜色样式,然后添加金色

document.getElementById(playerArray[0].id).style.background: gold;
document.getElementById(playerArray[1].id).style.background: #c0c0c0;
document.getElementById(playerArray[2].id).style.background: #cd7f32;;

As a side note, a front-end framework such as angular or react could allow you more more easily keep your ui updated based on the Javascript collection and with a more declarative syntax.

作为旁注,诸如 angular 或 react 之类的前端框架可以让您更轻松地根据 Javascript 集合和更具声明性的语法来更新 ui。

回答by Kashif Minhaj

A naive approach would be dynamically create HTML elements for each row in the leader board when the data (the scores) changes.

当数据(分数)发生变化时,一种简单的方法是为排行榜中的每一行动态创建 HTML 元素。

    <div id="leaderboard" class="container">
        <!-- scores will be inserted by the script here -->
    </div>
    <button onclick="randomize()">Randomize</button>
    <script src="script.js"></script>

script.js

脚本.js

let scores = [
    {name: "Player 1", score: 300},
    {name: "Player 2", score: 370},
    {name: "Player 3", score: 500},
    {name: "Player 4", score: 430},
    {name: "Player 5", score: 340},
];

function updateLeaderboardView() {
    let leaderboard = document.getElementById("leaderboard");
    leaderboard.innerHTML = "";

    scores.sort(function(a, b){ return b.score - a.score  });
    let elements = []; // we'll need created elements to update colors later on
    // create elements for each player
    for(let i=0; i<scores.length; i++) {
        let name = document.createElement("div");
        let score = document.createElement("div");
        name.classList.add("name");
        score.classList.add("score");
        name.innerText = scores[i].name;
        score.innerText = scores[i].score;

        let scoreRow = document.createElement("div");
        scoreRow.classList.add("row");
        scoreRow.appendChild(name);
        scoreRow.appendChild(score);
        leaderboard.appendChild(scoreRow);

        elements.push(scoreRow);

    }

    let colors = ["gold", "silver", "#cd7f32"];
    for(let i=0; i < 3; i++) {
        elements[i].style.color = colors[i];
    }
}

updateLeaderboardView();
function randomize() {
    for(var i=0; i<scores.length; i++) {
        scores[i].score = Math.floor(Math.random() * (600 - 300 + 1)) + 300;
    }
    // when your data changes, call updateLeaderboardView
    updateLeaderboardView();
}