简体   繁体   中英

Sort XML nodes with jQuery and then join them

Here is the basics of the schema... there is more than this, but this gives a good idea of what I need to accomplish:

<item>
    <name>This is some product name to sort with dictionary sort.</name>
    <price value="29.99">$29.99</price>
</item>
<item>
    <name>This is some product name to sort with dictionary sort.</name>
    <price value="29.99">$29.99</price>
</item>

Here is a down-and-dirty approach:

var node = null;
var path = null;
var items = jQuery( "item", xml );
var itemsTmp = new Array();
var itemsSorted = [];

for ( i = 0; i < items.length; i++ ) {

    // price
    itemsTmp[i] = jQuery( "price", items[i] ).attr( "value" );

}

itemsTmp.sort(function(a,b){return a-b});

for ( i=0;i<itemsTmp.length;i++ ) {

    itemsSorted[ i ] = jQuery( "price[value=" + itemsTmp[ i ] + "]", items ).parent();

}

The problem is that itemsSorted is now an array of jQuery objects. I need to get all of my item nodes back together, but sorted, so that later I can do:

jQuery( "item", xml ).each(function() {
    alert( jQuery( "price", this ).text() );
});

When adding to the itemsSorted array, you could use ...parent().get(0); To add the node to the array instead of the jQuery object.

Then after the last iteration:

jQuery("item", xml).remove();
jQuery.each(itemsSorted, function() {
    jQuery(xml).append(this);
});

Also, you should be aware that you haven't defined the variable 'i' in your for-loops. Which makes it a global variable, and can cause lots of strange behavior. I prefer to use the jQuery.each, because that also gives you local scope inside the for-loop :)

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