本文翻译自:JQuery .each() backwards
I'm using JQuery to select some elements on a page and then move them around in the DOM. 我正在使用JQuery在页面上选择一些元素,然后在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. 我遇到的问题是我需要按照JQuery自然要选择它们的相反顺序选择所有元素。 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? 我想选择所有的li项并对它们使用.each()命令,但是我想从第5项开始,然后是第4项等等。这可能吗?
#1楼
参考:https://stackoom.com/question/5qeC/JQuery-each-向后
#2楼
You cannot iterate backwards with the jQuery each function, but you can still leverage jQuery syntax. 你不能使用jQuery向后迭代每个函数,但你仍然可以利用jQuery语法。
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楼
$($("li").get().reverse()).each(function() { /* ... */ });
#4楼
You can do 你可以做
jQuery.fn.reverse = function() {
return this.pushStack(this.get().reverse(), arguments);
};
followed by 其次是
$(selector).reverse().each(...)
#5楼
Here are different options for this: 以下是不同的选项:
First : without jQuery: 第一 :没有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: ...和jQuery:
You can use this: 你可以用这个:
$($("ul > li").get().reverse()).each(function (i) {
$(this).text( 'Item ' + (++i));
});
Another way, using also jQuery with reverse is: 另一种方式,使用反向 jQuery是:
$.fn.reverse = [].reverse;
$("ul > li").reverse().each(function (i) {
$(this).text( 'Item ' + (++i));
});
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. 另一种选择是使用length
(匹配该选择器的元素的数量)并使用每次迭代的index
从那里向下移动。 Then you can use this: 然后你可以使用这个:
var $li = $("ul > li");
$li.each(function (i) {
$(this).text( 'Item ' + ($li.length - i));
});
One more , kind of related to the one above: 还有一种,与上述有关:
var $li = $("ul > li");
$li.text(function (i) {
return 'Item ' + ($li.length - i);
});
#6楼
我想你需要
.parentsUntill()