2014-07-11 2 views
0

XML 파일을 "glossary_term_heading"으로 어떻게 정렬 할 수 있습니까? 다른 예제를 살펴 보았지만 제대로 작동하지 않는 것 같습니다. 미리 감사드립니다.jQuery에서 XML 데이터 정렬

<glossary> 

<glossary_term> 
<glossary_term_heading><![CDATA[Title 1]]></glossary_term_heading> 
<glossary_term_content><![CDATA[<P>content 1</P>]]> 
</glossary_term_content> 
</glossary_term> 

<glossary_term> 
<glossary_term_heading><![CDATA[Title 2]]></glossary_term_heading> 
<glossary_term_content><![CDATA[<P>content 2</P>]]> 
</glossary_term_content> 
</glossary_term> 

</glossary> 

그리고 내 jQuery를 :

XML

당신은 용어의 배열을 얻고, 그것을 정렬하고 다음과 같이 정렬 된 배열을 반복 할 수

$(document).ready(function(){ 

    $.ajax({ 
     // Connect to the XML file 
     type: "GET", 
     url: "glossary.xml", 
     dataType: "xml", 
      success: function(xml) { 

      $(xml).find('glossary_term').each(function(){ // find each glossary term 
       var glossary_term_heading = $(this).find("glossary_term_heading").text(); // find the glossary term heading 
       var glossary_term_content = $(this).find("glossary_term_content").text(); // find the glossary term content 

       $('<h1 class="glossary_term_heading"></h1>').html(''+glossary_term_heading+'').appendTo('#page-wrap'); // add the glossary term heading into H1 tags 
       $('<div class="glossary_term_content"></div>').html(''+glossary_term_content+'').appendTo('#page-wrap'); // add the glossary term content into div 

       }); // xml.find end 

      } 

    }); // Ajax end 

답변

0

$.ajax({ 
    // Connect to the XML file 
    type: "GET", 
    url: "glossary.xml", 
    dataType: "xml", 
    success: function (xml) { 

     //find the terms array 
     var terms = $(xml).find('glossary_term').get(); 
     //sort the terms 
     terms.sort(function (t1, t2) { 
      var h1 = $.trim($(t1).find('glossary_term_heading').text()), 
       h2 = $.trim($(t2).find('glossary_term_heading').text()); 
      return h1.localeCompare(h2) 
     }) 

     //iterate over the sorted array 
     $.each(terms, function() { 
      var glossary_term_heading = $(this).find("glossary_term_heading").text(); // find the glossary term heading 
      var glossary_term_content = $(this).find("glossary_term_content").text(); // find the glossary term content 

      $('<h1 class="glossary_term_heading"></h1>').html('' + glossary_term_heading + '').appendTo('#page-wrap'); // add the glossary term heading into H1 tags 
      $('<div class="glossary_term_content"></div>').html('' + glossary_term_content + '').appendTo('#page-wrap'); // add the glossary term content into div 

     }); // xml.find end 

    } 

}); 

데모 : Fiddle

+0

아룬에게 감사드립니다 - 완벽하게 작동합니다. – user1004523