JQuery .each() backs

2022-08-29 23:12:20

我正在使用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等。这可能吗?


答案 1
$($("li").get().reverse()).each(function() { /* ... */ });

答案 2

我以世界上最小的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