How to sort DOM elements while selecting in jQuery?

后端 未结 4 1887
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 14:29

I have the following DIVs on my page:

Div 3
Div 2
相关标签:
4条回答
  • 2020-11-28 14:54

    I would use the Array.sort method. http://jsfiddle.net/LJWrg/

    var divArr = $("div[id*=pi_div]");
    function cleanId(id) {
        return parseInt(id.replace("pi_div",""),10);
    }
    Array.prototype.sort.call(divArr,function(a,b) {
        return cleanId(a.id) > cleanId(b.id);
    });
    divArr.each(function(){
        console.log(this.id);
    });
    

    jQuery does come with this method internally defined, so you can shorten it to this (however it uses undocumented methods) http://jsfiddle.net/LJWrg/1/:

    var divArr = $("div[id*=pi_div]");
    function cleanId(id) {
        return parseInt(id.replace("pi_div",""),10);
    }
    divArr.sort(function(a,b) {
        return cleanId(a.id) > cleanId(b.id);
    });
    divArr.each(function(){
        console.log(this.id);
    });
    
    0 讨论(0)
  • 2020-11-28 14:56
    $("div[id^=pi_div]").sort(function (a, b) {
        return a.id.replace('pi_div', '') > b.id.replace('pi_div', '');
    }).foo();
    

    http://jsfiddle.net/KrX7t/

    0 讨论(0)
  • 2020-11-28 15:01

    If you also want to sort them visibly on the page

    $('div[id^="pi_div"]').sort(function (a, b) {
        var re = /[^\d]/g;
        return ~~a.id.replace(re, '') > ~~b.id.replace(re, '');
    })
    .appendTo("#container");
    

    Note the ~~ which converts the values into integers, otherwise they would be compared as strings.

    See http://jsfiddle.net/Xjc2T/

    0 讨论(0)
  • 2020-11-28 15:03

    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.

    0 讨论(0)
提交回复
热议问题