JQuery .each()向后

本文翻译自: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));
});

Demo here 在这里演示

Another way, using also jQuery with reverse is: 另一种方式,使用反向 jQuery是:

$.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. 一种选择是使用length (匹配该选择器的元素的数量)并使用每次迭代的index从那里向下移动。 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 在这里演示


#6楼

我想你需要

.parentsUntill()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值