我正在尝试按字母顺序对游戏内的所有游戏对象进行排序,我有一个函数,我在哪里调用它,但我的按钮似乎没有执行任何 onclick 操作,想法是在访问该网站时不会对任何内容进行排序单击该按钮后,它会按标题字母顺序对所有游戏进行排序。我对 Javascript 还很陌生,任何关于比我当前的排序功能更好地实现这一点的建议都值得赞赏。下面是我的排序函数、事件监听器和 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>
最佳答案
通过一些重构,问题出现在 HTML 中,我在渲染数据之前调用该函数,导致该函数在 0 个对象的数组上工作,改变了我的按钮单击并将事件监听器添加到其余的位置其中正在初始化解决了该问题。下面是对我有用的更新后的 HTML 和 JS 函数。
<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()
}
}
关于javascript - 按字母顺序对游戏对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61511488/