jQuery .each()向后

我正在使用JQuery选择页面上的某些元素,然后在DOM中移动它们。我遇到的问题是我需要按照JQuery自然希望选择它们的相反顺序来选择所有元素。例如:

<ul>
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 3</li>
   <li>Item 4</li>
   <li>Item 5</li>
</ul>

我想选择所有li项目并在它们上使用.each()命令,但我要从项目5开始,然后从项目4开始,等等。这可能吗?

Mandy村村2020/03/14 18:02:42

I think u need

.parentsUntill()
泡芙A2020/03/14 18:02:42

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);
}
文韬武略辛弃疾2020/03/14 18:02:42

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
}
卡卡西Near2020/03/14 18:02:42

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

路易斯丁神奇2020/03/14 18:02:41

You can do

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

followed by

$(selector).reverse().each(...) 
梅Tony2020/03/14 18:02:41
$($("li").get().reverse()).each(function() { /* ... */ });