如何使用JS在data-attribute中按值排序元素 [英] How to sort out elements by their value in data- attribute using JS
问题描述
我需要整理已按升序显示的元素,以便重新排列。我需要通过data-val属性中的值对它们进行排序。
I need to sort out the elements that are already displayed in ascending order so that they just rearrange. I need to sort them out by the values in their data-val attributes.
<div id="a" class="item" data-val="6">Item a</div>
<div id="b" class="item" data-val="8">Item b</div>
<div id="c" class="item" data-val="2">Item c</div>
<div id="d" class="item" data-val="5">Item d</div>
<br />
<button onclick="sortOut()">Sort Out</button>
我在这里举了一个例子: http://jsfiddle.net/quatzael/uKnpa/
I made an example here: http://jsfiddle.net/quatzael/uKnpa/
我不知道该怎么做。我有点开始,但可能是错误的。
I dont know how to do that. I kind of started but it is probably wrong.
我需要函数首先找出哪个元素叫做item这个类,然后用这个类进行排序data-val属性的值。
I need the function to firstly find out what elements have class called "item" and then those with this class sort out by the value of their data-val attribute.
它必须适用于所有浏览器,因此解决方案可能涉及.appendChild()
It has to work in all browsers so the solution should probably involve .appendChild()
Tnx任何帮助..
Tnx for any help..
推荐答案
您需要以新排序的顺序将它们附加到DOM 。
You need to append them to the DOM in the newly sorted order.
以下是我在您的代码中添加的内容:
Here's what I added to your code to do this:
divs.sort(function(a, b) {
return a.dataset.val.localeCompare(b.dataset.val);
});
var br = document.getElementsByTagName("br")[0];
divs.forEach(function(el) {
document.body.insertBefore(el, br);
});
appendChild()
方法可能是用于代替 .insertBefore()
如果您的已排序项目在一个没有其他内容的容器中。
The appendChild()
method could be used instead of .insertBefore()
if your sorted items were in a container with nothing else.
支持更旧浏览器,您将使用 .getAttribute(data-val)
而不是 .dataset.val
。
To support older browsers, you would use .getAttribute("data-val")
instead of .dataset.val
.
如果你想要数字排序,你不应该在 .sort中使用
function。 .localeCompare
()
And if you want a numeric sorting, you shouldn't use .localeCompare
in the .sort()
function.
这篇关于如何使用JS在data-attribute中按值排序元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!