我正在使用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开始,等等。这可能吗?
我正在使用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开始,等等。这可能吗?
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);
}
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
}
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
You can do
jQuery.fn.reverse = function() {
return this.pushStack(this.get().reverse(), arguments);
};
followed by
$(selector).reverse().each(...)
$($("li").get().reverse()).each(function() { /* ... */ });
I think u need