jQuery .each()向后

JavaScript

老丝小胖蛋蛋

2020-03-14

我正在使用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开始,等等。这可能吗?

第1588篇《jQuery .each()向后》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

6个回答
Mandy村村 2020.03.14

I think u need

.parentsUntill()
泡芙A 2020.03.14

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

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
}
卡卡西Near 2020.03.14

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

You can do

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

followed by

$(selector).reverse().each(...) 
梅Tony 2020.03.14
$($("li").get().reverse()).each(function() { /* ... */ });

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android