我正在制作这个菜单页面,使用 wordpress 作为后端。所以我获取了元素,将它们放入模板并将它们附加到父级,但现在我需要弄清楚如何按字母顺序对菜单项进行排序。我不知道是否应该在获取和追加之后编写新函数,或者将排序作为获取和追加数据的函数系列的一部分。
这是我用过的:
const template = document.querySelector("#menutemplate").content;
const newSection = document.createElement("section");
const parent = document.querySelector("main");
function getMenu() {
fetch("MY LINK GOES HERE")
.then(res => res.json())
.then(showMenu)
}
function showMenu(menuItems) {
//console.log(menuItems)
menuItems.forEach(showItem)
}
function showItem(item) {
//console.log(item)
const clone = template.cloneNode(true);
clone.querySelector(".product").textContent=item.title.rendered
clone.querySelector(".price").textContent=item.acf.volunteer_price + " dkk";
newSection.appendChild(clone);
parent.appendChild(newSection);
}
getMenu();
最佳答案
你可以使用 Array.prototype.sort
吗?
function showMenu(menuItems) {
menuItems
.sort(a, b) => a.title.localeCompare(b.title))
.forEach(showItem)
}
关于Javascript 排序获取的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53461641/