如何按数据属性的数值对元素进行排序? [英] How can I sort elements by numerical value of data attribute?
本文介绍了如何按数据属性的数值对元素进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我具有属性为data-percentage
的多个元素,有没有一种方法可以先使用JavaScript或jQuery将这些元素按最低值升序排列?
I have multiple elements with the attribute: data-percentage
, is there a way of sorting the elements into ascending order with the lowest value first using either JavaScript or jQuery?
HTML:
<div class="testWrapper">
<div class="test" data-percentage="30">
<div class="test" data-percentage="62">
<div class="test" data-percentage="11">
<div class="test" data-percentage="43">
</div>
所需结果:
<div class="testWrapper">
<div class="test" data-percentage="11">
<div class="test" data-percentage="30">
<div class="test" data-percentage="43">
<div class="test" data-percentage="62">
</div>
推荐答案
使用 Array.sort
:
var $wrapper = $('.testWrapper');
$wrapper.find('.test').sort(function(a, b) {
return +a.dataset.percentage - +b.dataset.percentage;
})
.appendTo($wrapper);
这是小提琴: http://jsfiddle.net/UdvDD/
如果您使用的是IE< 10,您不能使用dataset
属性.使用getAttribute
代替:
If you're using IE < 10, you can't use the dataset
property. Use getAttribute
instead:
var $wrapper = $('.testWrapper');
$wrapper.find('.test').sort(function(a, b) {
return +a.getAttribute('data-percentage') - +b.getAttribute('data-percentage');
})
.appendTo($wrapper);
这是小提琴: http://jsfiddle.net/UdvDD/1/
这篇关于如何按数据属性的数值对元素进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文