Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

javascript - How can I sort elements by numerical value of data attribute?

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>

Desired result:

<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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use Array.sort:

var $wrapper = $('.testWrapper');

$wrapper.find('.test').sort(function(a, b) {
    return +a.dataset.percentage - +b.dataset.percentage;
})
.appendTo($wrapper);

Here's the fiddle: http://jsfiddle.net/UdvDD/


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);

Here's the fiddle: http://jsfiddle.net/UdvDD/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...