在 jQuery 中选择时如何对 DOM 元素进行排序? [英] How to sort DOM elements while selecting in jQuery?

查看:28
本文介绍了在 jQuery 中选择时如何对 DOM 元素进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面上有以下 DIV:

第 3 部分

<div id="pi_div2">第 2 部分

<div id="pi_div1">第 1 部分

<div id="pi_div6">第 6 部分

<div id="pi_div5">第 5 部分

<div id="pi_div4">第 4 部分

我正在尝试使用 jQuery 代码 $("div[id*=pi_div]") 选择 Div.

当我在选择器上执行 each() 时,我需要根据它们的 ID 对 div 进行排序.当我遍历 DIV 时,顺序应该是:PI_DIV1、PI_DIV2、PI_DIV3、PI_DIV4、PI_DIV5、PI_DIV6.我怎样才能在 jQuery 中做到这一点?

解决方案

您可以调用 .sort() 在调用 .each()

之前

$("div[id*=pi_div]").sort(function(a,b){如果(a.id < b.id){返回-1;} 别的 {返回 1;}}).each(function() { console.log($(this).attr("id"));});

我想知道为什么其他答案要删除 id 的 pi_div 部分,我明白了.如果根据字符串"进行比较,pi_div10 将排在 pi_div2 之前.

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>

I am trying to select the Divs using the jQuery code $("div[id*=pi_div]").

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"));});

EDIT: 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屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆