JQuery .each() backwards

前端 未结 11 1075
萌比男神i
萌比男神i 2020-11-22 13:44

I\'m using JQuery to select some elements on a page and then move them around in the DOM. The problem I\'m having is I need to select all the elements in the reverse order t

相关标签:
11条回答
  • 2020-11-22 14:25

    I prefer creating a reverse plug-in eg

    jQuery.fn.reverse = function(fn) {       
       var i = this.length;
    
       while(i--) {
           fn.call(this[i], i, this[i])
       }
    };
    

    Usage eg:

    $('#product-panel > div').reverse(function(i, e) {
        alert(i);
        alert(e);
    });
    
    0 讨论(0)
  • 2020-11-22 14:27

    I present you with the cleanest way ever, in the form of the world's smallest jquery plugin:

    jQuery.fn.reverse = [].reverse;
    

    Usage:

    $('jquery-selectors-go-here').reverse().each(function () {
        //business as usual goes here
    });
    

    -All credit to Michael Geary in his post here: http://www.mail-archive.com/discuss@jquery.com/msg04261.html

    0 讨论(0)
  • 2020-11-22 14:28

    Here are different options for this:

    First: without jQuery:

    var lis = document.querySelectorAll('ul > li');
    var contents = [].map.call(lis, function (li) {
        return li.innerHTML;
    }).reverse().forEach(function (content, i) {
        lis[i].innerHTML = content;
    });
    

    Demo here

    ... and with jQuery:

    You can use this:

    $($("ul > li").get().reverse()).each(function (i) {
        $(this).text( 'Item ' + (++i));
    });
    

    Demo here

    Another way, using also jQuery with reverse is:

    $.fn.reverse = [].reverse;
    $("ul > li").reverse().each(function (i) {
        $(this).text( 'Item ' + (++i));
    });
    

    This demo here.

    One more alternative is to use the length (count of elements matching that selector) and go down from there using the index of each iteration. Then you can use this:

    var $li = $("ul > li");
    $li.each(function (i) {
        $(this).text( 'Item ' + ($li.length - i));
    });
    

    This demo here

    One more, kind of related to the one above:

    var $li = $("ul > li");
    $li.text(function (i) {
        return 'Item ' + ($li.length - i);
    });
    

    Demo here

    0 讨论(0)
  • 2020-11-22 14:35
    $($("li").get().reverse()).each(function() { /* ... */ });
    
    0 讨论(0)
  • 2020-11-22 14:37

    You can do

    jQuery.fn.reverse = function() {
        return this.pushStack(this.get().reverse(), arguments);
    }; 
    

    followed by

    $(selector).reverse().each(...) 
    
    0 讨论(0)
提交回复
热议问题