简体   繁体   中英

How to sort $(xml).children()?

How can i sort xml elements by tagName (nodeName) when i call $(xml).children()?

I was hoping i can do something like $(xml).children().sort() but that doesn't seem to work.

Here's an example: ( http://jsfiddle.net/bdMn3/1/ )

Code:

var xml = "<data><itemB>more data</itemB><itemC>yes, more data</itemC><itemA>some data</itemA></data>";

var info = $("#info");

$(xml).children().each(function () {
    var xmlnode = $(this);
    info.append(this.tagName + " - " + xmlnode.text() + "<br/>");
});

Current Results:

ITEMB - more data
ITEMC - yes, more data
ITEMA - some data

Desired Results:

ITEMA - some data
ITEMB - more data
ITEMC - yes, more data

sort函数将比较函数作为参数。

$(xml).children().sort(function(a, b) { return a.tagName > b.tagName ? 1 : a.tagName < b.tagName ? -1 : 0; })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM