我有一个名字列表,我想根据它们的点数进行排序,默认设置为0
,每次我按下一个按钮,它就会给特定的名字加一个点数,但不会将它们排在第一位,如果我在js
列表中手动添加点数,它可以正常工作,但当我使用按钮时就不行了。 下面是我尝试的方法:
null
let characters = [
{name: document.getElementById("name 1").textContent, points: 0},
{name: document.getElementById("name 2").textContent, points: 0},
{name: document.getElementById("name 3").textContent, points: 0}
];
function choice (button) {
const buttonCharacterObject = characters.find(obj => obj.name === button.textContent);
buttonCharacterObject.points += 1;
console.log(characters)
}
const ranking = characters.sort((a, b) => (a.points < b.points ? 1 : -1));
console.log(ranking);
<button id="name 1" onclick="choice(this)">John</button>
<button id="name 2" onclick="choice(this)">Martin</button>
<button id="name 3" onclick="choice(this)">Sam</button>
null
只需将排名也放入函数中,控制台输出已排名的字符。
null
let characters = [
{name: document.getElementById("name 1").textContent, points: 0},
{name: document.getElementById("name 2").textContent, points: 0},
{name: document.getElementById("name 3").textContent, points: 0}
];
function choice (button) {
const buttonCharacterObject = characters.find(obj => obj.name === button.textContent);
buttonCharacterObject.points += 1;
const ranking = characters.sort((a, b) => (a.points < b.points ? 1 : -1));
console.log(ranking);
}
<button id="name 1" onclick="choice(this)">John</button>
<button id="name 2" onclick="choice(this)">Martin</button>
<button id="name 3" onclick="choice(this)">Sam</button>
增加点数后,需要在choice()
方法中进行排序。
请尝试以下操作:
function choice (button) {
const buttonCharacterObject = characters.find(obj => obj.name === button.textContent);
buttonCharacterObject.points += 1;
characters.sort((a, b) => (a.points < b.points ? 1 : -1));
console.log(characters)
}