如何使用JS在data-attribute中按值排序元素 [英] How to sort out elements by their value in data- attribute using JS

查看:187
本文介绍了如何使用JS在data-attribute中按值排序元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要整理已按升序显示的元素,以便重新排列。我需要通过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);
});

http://jsfiddle.net/RZ2K4/

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中使用 .localeCompare () function。

And if you want a numeric sorting, you shouldn't use .localeCompare in the .sort() function.

这篇关于如何使用JS在data-attribute中按值排序元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆