HTML5 Data Attribute Sort

前端 未结 2 1300
感情败类
感情败类 2021-01-05 06:58

I\'d like to sort DOM elements that has data attributes defined for rating and date. What is the best way to implement sorting on the front-end with jQuery?

Sample

2条回答
  •  别那么骄傲
    2021-01-05 07:25

    Here is the basic idea...

    var sortedSet = $('#sort li').toArray().sort(function(a, b) {
       return $(a).data('rating') - $(b).data('rating');
    });
    

    You select the elements, convert them to a proper array, and then sort (the comparison function I used is an example, change it to suit your requirements).

    jsFiddle with lowest button.

提交回复
热议问题