JQuery .each() backwards

前端 未结 11 1074
萌比男神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:10

    You cannot iterate backwards with the jQuery each function, but you can still leverage jQuery syntax.

    Try the following:

    //get an array of the matching DOM elements   
    var liItems = $("ul#myUL li").get();
    
    //iterate through this array in reverse order    
    for(var i = liItems.length - 1; i >= 0; --i)
    {
      //do Something
    }
    
    0 讨论(0)
  • 2020-11-22 14:17

    I found Array.prototype.reverse unsuccessful with objects, so I made a new jQuery function to use as an alternative: jQuery.eachBack(). It iterates through as the normal jQuery.each() would, and stores each key into an array. It then reverses that array and performs the callback on the original array/object in the order of the reversed keys.

    jQuery.eachBack=function (obj, callback) {
        var revKeys=[]; $.each(obj,function(rind,rval){revKeys.push(rind);}); 
        revKeys.reverse();
        $.each(revKeys,function (kind,i){
            if(callback.call(obj[i], i, obj[i]) === false) {    return false;}
        });
        return obj;
    }   
    jQuery.fn.eachBack=function (callback,args) {
        return jQuery.eachBack(this, callback, args);
    }
    
    0 讨论(0)
  • 2020-11-22 14:19

    Needed to do a reverse on $.each so i used Vinay idea:

    //jQuery.each(collection, callback) =>
    $.each($(collection).get().reverse(), callback func() {});
    

    worked nicely, thanks

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

    You can also try

    var arr = [].reverse.call($('li'))
    arr.each(function(){ ... })
    
    0 讨论(0)
  • 2020-11-22 14:21

    I think u need

    .parentsUntill()
    
    0 讨论(0)
  • 2020-11-22 14:23

    If you don't want to save method into jQuery.fn you can use

    [].reverse.call($('li'));
    
    0 讨论(0)
提交回复
热议问题