开发者

how to sort xml data in jQuery

开发者 https://www.devze.com 2023-01-03 11:37 出处:网络
how can i sort all officers based on their ranks jQuery $.get(\'officers.xml\', function(grade){ $(grade).find(\'officer\').each(function(){

how can i sort all officers based on their ranks

jQuery

$.get('officers.xml', function(grade){
    $(grade).find('officer').each(function(){
        var $rank = $(this).attr('rank');
    });
});

XML (officer.xml)

<grade>
 <officer rank="2"></student>
 <officer rank="3">开发者_JS百科;</student>
 <officer rank="1"></student>
</grade>

thanks.


$.get('officers.xml', function(grade){     
  var officer = $(grade).find('officer');

  officer.sort(function(a, b){
     return (parseInt($(a).attr('rank')) - parseInt($(b).attr('rank')));
  });

  officer.each(function(i,v){
    alert($(v).attr('rank'));
  });
});    


In case you generate dynamically your xml file on the server the best way is to sort data on the server side. Some discussion is here.


Something like this should work

var officers = $('officer'); // unsorted

function matchRank(a, b) {
    return (int)a.attr('rank') - (int)b.attr('rank');
};

officers.sort(matchRank); // sorted
0

精彩评论

暂无评论...
验证码 换一张
取 消