开发者

Jquery reverse sorting

开发者 https://www.devze.com 2023-02-18 21:06 出处:网络
I have this code: $(document).ready(function() { ofertas_sort = function(sort_key) { // array of offer divs

I have this code:

 $(document).ready(function() {
        ofertas_sort = function(sort_key) {
            // array of offer divs
            var ofertas = $('.infoferta');

            // the div classname corresponding to the key by which
            // we are sorting
            var sort_key_sel = 'div.' + sort_key;

            // in large lists it'd be more efficient to calculate
            // this data pre-sort, but for this instance it's fine
            ofertas.sort(function(a, b) {
                return parseInt($(sort_key_sel, a).attr('data-value')) -
                    parseInt($(sort_key_sel, b).attr('data-value'));
            });

            // re-fill the container with the newly-sorted divs
            $('#ofertas_container').empty().append(ofertas);
        };

        $('a').click(function() {
            ofertas_sort($(this).attr('data-key'));
        });
    });

I need to do the reverse.. but when i put lines like this:

 ofertas.reverse(function(i, e) {
            alert(i);
            al开发者_运维知识库ert(e);
        });

it shows this message

Uncaught TypeError: Object [object Object] has no method 'reverse'


ofertas is not an array -- it is a jQuery object -- and is missing such a method called reverse (see jQuery API). Likewise, I am surprised the posted example code works because sort is being invoked upon ofertas.

To "reverse sort" just multiply the result of the comparator (sort function) by -1 or invert the operands of the subtraction operation (which is effectively the same thing here).

Happy coding.


ofertas is a jQuery object, however you can convert it to an array by using the toArray() method. From there you can call array functions such as reverse.

0

精彩评论

暂无评论...
验证码 换一张
取 消