我想问一下,如何按照"glossary_term_heading“对我的XML文件进行排序?我看过其他例子,但似乎无法让它发挥作用。提前谢谢。
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:
$(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发布于 2014-07-11 04:51:40
您可以获得一个术语数组,并对其排序,然后对排序后的数组进行迭代,如下
$.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
}
});演示:小提琴
https://stackoverflow.com/questions/24690148
复制相似问题