JQuery .each() backwards

2018-12-31 15:38发布

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 that JQuery naturally wants to select them. For example:

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

I want to select all the li items and use the .each() command on them but I want to start with Item 5, then Item 4 etc. Is this possible?

12条回答
与风俱净
2楼-- · 2018-12-31 15:48

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
}
查看更多
柔情千种
3楼-- · 2018-12-31 15:50

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

查看更多
姐姐魅力值爆表
4楼-- · 2018-12-31 15:51

I think u need

.parentsUntill()
查看更多
不再属于我。
5楼-- · 2018-12-31 15:52
$($("li").get().reverse()).each(function() { /* ... */ });
查看更多
不再属于我。
6楼-- · 2018-12-31 15:53

Here are different options for this:

First: without jQuery:

var lis = document.querySelectorAll('ul > li');
var contents = [].map.call(lis, function (li) {
    return li.innerHTML;
}).reverse().forEach(function (content, i) {
    lis[i].innerHTML = content;
});

Demo here

... and with jQuery:

You can use this:

$($("ul > li").get().reverse()).each(function (i) {
    $(this).text( 'Item ' + (++i));
});

Demo here

Another way, using also jQuery with reverse is:

$.fn.reverse = [].reverse;
$("ul > li").reverse().each(function (i) {
    $(this).text( 'Item ' + (++i));
});

This demo here.

One more alternative is to use the length (count of elements matching that selector) and go down from there using the index of each iteration. Then you can use this:

var $li = $("ul > li");
$li.each(function (i) {
    $(this).text( 'Item ' + ($li.length - i));
});

This demo here

One more, kind of related to the one above:

var $li = $("ul > li");
$li.text(function (i) {
    return 'Item ' + ($li.length - i);
});

Demo here

查看更多
一个人的天荒地老
7楼-- · 2018-12-31 15:53

I recognize that jQuery supports and encourages plugins. That said, you may find this article relevant: Don’t modify objects you don’t own. In this case at least, I opted not to extend jQuery on the off chance that another plugin defines reverse differently.

Here's a simple solution that doesn't extend the jQuery object.

function jqueryReverse( set ) {

    return [].reverse.call( set );
}

console.log( jqueryReverse( $( 'li' ) ) );
查看更多
登录 后发表回答