これにはさまざまなオプションがあります。
最初: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);
});
デモはこちら