本文介绍了按数据属性的数值对元素进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有多个具有属性的元素: data-percentage
,有没有一种方法可以将元素按升序排序,并且值最小?
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?
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>
所需结果:
HTML:
Desired result:HTML:
<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>
使用Javascript还是jQuery?
using either Javascript or jQuery?
推荐答案
使用:
var $wrapper = $('.testWrapper');
$wrapper.find('.test').sort(function(a, b) {
return +a.dataset.percentage - +b.dataset.percentage;
})
.appendTo($wrapper);
以下是小提琴:
如果你正在使用IE< 10,您不能使用数据集
属性。改为使用 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);
这是小提琴:
这篇关于按数据属性的数值对元素进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!