我有以下标记:
<ul>
<li class="category-item" data-category-group="jeans">Bottoms</li>
<li class="category-item" data-category-group="tops">Shirt</li>
<li class="category-item" data-category-group="jeans">Jeans</li>
<li class="category-item" data-category-group="jeans">Shorts</li>
<li class="category-item" data-category-group="tops">Hoodie</li>
<li class="category-item" data-category-group="accesories">Sunglasses</li>
</ul>
元素在data-category-group
属性中可以具有不同的组名。我希望能够对元素进行排序,以使带有牛仔裤组的元素在DOM中都紧随其后。
我有个主意试图通过将HTML集合转换为数组然后对其进行排序来解决此问题。但是它似乎不能那样工作。
这是我的JavaScript:
var categoryItems = document.querySelectorAll("[data-category-group]");
var categoryItemsArray = Array.from(categoryItems)
document.getElementById("demo").innerHTML = categoryItemsArray;
function myFunction() {
categoryItemsArray.sort();
document.getElementById("demo").innerHTML = categoryItemsArray;
}
这怎么实现?
答案 0 :(得分:6)
您可以(并且应该)使用Array#sort
,只需向其传递一个检查data-category-group
属性的函数即可:
var categoryItems = document.querySelectorAll("[data-category-group]");
var categoryItemsArray = Array.from(categoryItems);
let sorted = categoryItemsArray.sort(sorter);
function sorter(a,b) {
if(a.dataset.categoryGroup < b.dataset.categoryGroup) return -1;
if(a.dataset.categoryGroup > b.dataset.categoryGroup) return 1;
}
document.querySelector("button").onclick = () => sorted.forEach(e => document.querySelector("#demo").appendChild(e));
<ul id="demo">
<li class="category-item" data-category-group="jeans">Bottoms</li>
<li class="category-item" data-category-group="tops">Shirt</li>
<li class="category-item" data-category-group="jeans">Jeans</li>
<li class="category-item" data-category-group="jeans">Shorts</li>
<li class="category-item" data-category-group="tops">Hoodie</li>
<li class="category-item" data-category-group="accesories">Sunglasses</li>
</ul>
<button>Sort Elements</button>
答案 1 :(得分:4)
您可以使用数组上的sort
方法执行此操作,然后将元素附加回ul
。
let ul = document.querySelector("ul");
let li = ul.querySelectorAll("li");
let sorted = Array.from(li).sort((a, b) => {
return (b.dataset.categoryGroup == 'jeans') - (a.dataset.categoryGroup == 'jeans')
})
ul.innerHTML = "";
sorted.forEach(e => ul.appendChild(e))
<ul>
<li class="category-item" data-category-group="jeans">Bottoms</li>
<li class="category-item" data-category-group="tops">Shirt</li>
<li class="category-item" data-category-group="jeans">Jeans</li>
<li class="category-item" data-category-group="jeans">Shorts</li>
<li class="category-item" data-category-group="tops">Hoodie</li>
<li class="category-item" data-category-group="accesories">Sunglasses</li>
</ul>