464

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 などにしたいのですが、これは可能ですか?

4

11 に答える 11

716
$($("li").get().reverse()).each(function() { /* ... */ });
于 2009-09-08T13:31:07.933 に答える
420

世界最小の jquery プラグインという形で、これまでで最もクリーンな方法を紹介します。

jQuery.fn.reverse = [].reverse;

使用法:

$('jquery-selectors-go-here').reverse().each(function () {
    //business as usual goes here
});

-Michael Geary のすべての功績は、こちらの投稿にあります: http://www.mail-archive.com/discuss@jquery.com/msg04261.html

于 2011-03-22T02:42:20.860 に答える
64

できるよ

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

に続く

$(selector).reverse().each(...) 
于 2009-09-08T13:34:06.213 に答える
21

これにはさまざまなオプションがあります。

最初: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;
});

デモはこちら

...そしてjQueryで:

これを使用できます:

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

デモはこちら

にjQueryも使用する別の方法は次のとおりです。

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

このデモはこちら.

もう 1 つの代替方法は、length(そのセレクターに一致する要素の数) を使用しindex、各反復の を使用してそこから下に移動することです。次に、これを使用できます:

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

このデモはこちら

もう1つ、上記のものに関連する種類:

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

デモはこちら

于 2013-08-19T18:22:56.443 に答える
14

リバース プラグインを作成することを好みます。

jQuery.fn.reverse = function(fn) {       
   var i = this.length;

   while(i--) {
       fn.call(this[i], i, this[i])
   }
};

使用例:

$('#product-panel > div').reverse(function(i, e) {
    alert(i);
    alert(e);
});
于 2010-12-21T14:03:29.190 に答える
5

$.each を逆にする必要があったので、Vinay のアイデアを使用しました。

//jQuery.each(collection, callback) =>
$.each($(collection).get().reverse(), callback func() {});

うまくいきました、ありがとう

于 2010-06-17T04:00:31.533 に答える
4

jQuery の each 関数を逆方向に繰り返すことはできませんが、jQuery 構文を利用することはできます。

次のことを試してください。

//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
}
于 2009-09-08T13:30:22.070 に答える