在jQuery中进行选择时如何对DOM元素进行排序? [英] How to sort DOM elements while selecting in jQuery?
问题描述
我的页面上有以下DIV:
I have the following DIVs on my page:
<div id="pi_div3">
Div 3
</div>
<div id="pi_div2">
Div 2
</div>
<div id="pi_div1">
Div 1
</div>
<div id="pi_div6">
Div 6
</div>
<div id="pi_div5">
Div 5
</div>
<div id="pi_div4">
Div 4
</div>
我正在尝试使用jQuery代码$("div[id*=pi_div]")
选择Divs.
I am trying to select the Divs using the jQuery code $("div[id*=pi_div]")
.
当我在选择器上执行each()时,我需要根据其ID对div进行排序.当我遍历DIV时,顺序应为:PI_DIV1,PI_DIV2,PI_DIV3,PI_DIV4,PI_DIV5,PI_DIV6.如何在jQuery中做到这一点?
I need the divs to be sorted based on their IDs when I do an each() on the selector. When I loop through the DIVs, the order should be: PI_DIV1, PI_DIV2, PI_DIV3, PI_DIV4, PI_DIV5, PI_DIV6. How can I do that in jQuery?
推荐答案
You can call .sort() before calling .each()
$("div[id*=pi_div]").sort(function(a,b){
if(a.id < b.id) {
return -1;
} else {
return 1;
}
}).each(function() { console.log($(this).attr("id"));});
我想知道为什么其他答案正在删除id的pi_div
部分,我知道了.如果您根据字符串"进行比较,则pi_div10
将排在pi_div2
之前.
I was wondering why the other answers are removing the pi_div
part of the id and I get it. If you compare based on the "strings" pi_div10
will come before pi_div2
.
这篇关于在jQuery中进行选择时如何对DOM元素进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!