Jac*_*lls 432 javascript arrays jquery reverse
我正在使用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>
Run Code Online (Sandbox Code Playgroud)
我想选择所有的li项目并对它们使用.each()命令,但我想从第5项开始,然后是项目4等.这可能吗?
Joe*_*ung 667
$($("li").get().reverse()).each(function() { /* ... */ });
Run Code Online (Sandbox Code Playgroud)
Wal*_*ton 400
我用最干净的方式呈现给你,以世界上最小的jquery插件的形式:
jQuery.fn.reverse = [].reverse;
Run Code Online (Sandbox Code Playgroud)
用法:
$('jquery-selectors-go-here').reverse().each(function () {
//business as usual goes here
});
Run Code Online (Sandbox Code Playgroud)
- Michael Geary在他的帖子中的所有功劳:http://www.mail-archive.com/discuss@jquery.com/msg04261.html
Vin*_*jip 63
你可以做
jQuery.fn.reverse = function() {
return this.pushStack(this.get().reverse(), arguments);
};
Run Code Online (Sandbox Code Playgroud)
其次是
$(selector).reverse().each(...)
Run Code Online (Sandbox Code Playgroud)
Ser*_*gio 20
以下是不同的选项:
第一:没有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;
});
Run Code Online (Sandbox Code Playgroud)
...和jQuery:
你可以用这个:
$($("ul > li").get().reverse()).each(function (i) {
$(this).text( 'Item ' + (++i));
});
Run Code Online (Sandbox Code Playgroud)
在这里演示
另一种方式,使用反向 jQuery 是:
$.fn.reverse = [].reverse;
$("ul > li").reverse().each(function (i) {
$(this).text( 'Item ' + (++i));
});
Run Code Online (Sandbox Code Playgroud)
这个演示在这里.
另一种选择是使用length(匹配该选择器的元素的数量)并使用index每次迭代从那里向下移动.然后你可以使用这个:
var $li = $("ul > li");
$li.each(function (i) {
$(this).text( 'Item ' + ($li.length - i));
});
Run Code Online (Sandbox Code Playgroud)
这个演示在这里
还有一种,与上述有关:
var $li = $("ul > li");
$li.text(function (i) {
return 'Item ' + ($li.length - i);
});
Run Code Online (Sandbox Code Playgroud)
在这里演示
Jam*_*ate 14
我更喜欢创建一个反向插件,例如
jQuery.fn.reverse = function(fn) {
var i = this.length;
while(i--) {
fn.call(this[i], i, this[i])
}
};
Run Code Online (Sandbox Code Playgroud)
用法例如:
$('#product-panel > div').reverse(function(i, e) {
alert(i);
alert(e);
});
Run Code Online (Sandbox Code Playgroud)
小智 5
需要对$ .each进行反向操作,因此我使用了Vinay的想法:
//jQuery.each(collection, callback) =>
$.each($(collection).get().reverse(), callback func() {});
Run Code Online (Sandbox Code Playgroud)
工作很好,谢谢
| 归档时间: |
|
| 查看次数: |
194640 次 |
| 最近记录: |