I know this kind of question has been asked before, but the general solution of
$($("input").get().reverse()).each(function() { /* ... */ });
is not working for me. I have an xml document that contains a list of concerts that I'd like to display on a webpage. So, in JQuery:
$.ajax({
type: "GET",
url: "concerts.xml",
dataType: "xml",
cache: false,
success: function(xml) {
$(xml).find('concert').each(function() {
/*do stuff*/
});
}
});
However, I'd like to display the concerts in reverse order. So, I tried the following, but it did not work:
$.ajax({
type: "GET",
url: "concerts.xml",
dataType: "xml",
cache: false,
success: function(xml) {
$($(xml).find('concert').reverse()).each(function() {
/*do stuff*/
});
}
});
Any assistance would be much appreciated. Thanks.
You excluded the call to the get()[docs] method.
// --------------------v
$($(xml).find('concert').get().reverse()).each(function() {
This is needed to get an Array of the elements from the jQuery object. This is what allows you to call .reverse(), which is on Array.prototype.
To walk through the items in reverse order, why not just use code like this:
var data = $("input");
for (var i = data.length - 1; i >= 0; i--) {
var item = data[i];
// do whatever you want to do with item here
}
Or, if you want to make a function out of it that takes a jQuery object and your function:
function reverseEach(jQueryObj, fn) {
for (var i = jQueryObj.length - 1; i >= 0; i--) {
if (fn.call(jQueryObj[i], i, jQueryObj[i]) === false) {
break;
}
}
}
So, you could then call:
reverseEach($(xml).find('concert'), function() {
// do stuff here
});
or:
reverseEach($("input"), function() {
// do stuff here
});
Or, you could even make reverseEach a jQuery plugin if you wanted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With