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

前端 未结 5 997
清歌不尽
清歌不尽 2020-11-27 03:07

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 eit

5条回答
  •  忘掉有多难
    2020-11-27 03:34

    A more robust option, this function can allow you to sort elements based on multiple options.

    https://jsfiddle.net/L3rv3y7a/1/

    // This calls the function
    DOYPSort('#wrapper', '.element', value, order);
    
        // Parameters must be strings
        // Order of must be either 'H' (Highest) or 'L' (Lowest)
        function DOYPSort(wrapper, elementtosort, AttrToSort, orderof) {
            $(wrapper).find(elementtosort).sort(function (a, b) {
                if (orderof === 'H') {
                    return +b.getAttribute(AttrToSort) - +a.getAttribute(AttrToSort);
                } 
                if (orderof === 'L') {
                    return +a.getAttribute(AttrToSort) - +b.getAttribute(AttrToSort);
                }
            }).appendTo(wrapper);
        }
    

提交回复
热议问题