[英]Sort game objects alphabetically
我正在尝试按字母顺序对游戏中的所有游戏对象进行排序我有一个 function 用于它,我在哪里调用它,但我的按钮似乎没有做任何事情 onclick 这个想法是在访问该站点时没有任何排序,然后一旦你点击该按钮按标题按字母顺序对所有游戏进行排序。 我对 Javascript 还是新手,任何关于实现这一点的建议都比我目前的排序 function 表示赞赏。 下面是我的代码片段,用于排序 function 事件侦听器和 html 实现。
*编辑1:我已经重构了一点,当单击按钮时它返回为未定义。 添加我的 2 个片段,因为我现在以不同的方式执行它。
sortAlpha() {
this.games.sort(function(gameA, gameB){
if (gameA.title < gameB.title) {
return -1;
}
if (gameA.title > gameB.title){
return 1;
}
return 0;
});
window.onload = function() {
document.getElementById("filter").onclick = sortAlpha;
}
}
<div id="filter">
<div id="buttons">
<button onclick="sortAlpha()">Sort Games Alphabetically</button>
</div>
</div>
With some refactoring what was becoming an issue was within the HTML I was calling the function before the data was being rendered causing the function to work on an array of 0 objects altering my button click and adding the event listener to where the rest of them were正在初始化解决了这个问题。 下面是更新后的 HTML 和 JS Function 对我有用。
<div id="filter">
<div id="buttons">
<button id="sort">Sort Games Alphabetically</button>
</div>
</div>
document.getElementById("sort").addEventListener ("click", this.sortAlpha.bind(this));
console.log('test')
this.games.sort(function(gameA, gameB){
if (gameA.title < gameB.title) {
return -1;
}
if (gameA.title > gameB.title){
return 1;
}
return 0;
});
console.log(this.games)
const gamesContainer = document.getElementById('games-content')
gamesContainer.innerHTML = ""
this.renderGames()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.