【问题标题】:Sort XML nodes with jQuery and then join them使用 jQuery 对 XML 节点进行排序,然后加入它们
【发布时间】:2010-10-28 00:13:38
【问题描述】:

这里是架构的基础知识......还有更多,但这很好地说明了我需要完成的工作:

<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>

这是一个低俗的方法:

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();

}

问题是 itemsSorted 现在是一个 jQuery 对象数组。我需要将所有项目节点重新组合在一起,但已排序,以便稍后我可以这样做:

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

【问题讨论】:

    标签: javascript jquery sorting


    【解决方案1】:

    添加到 itemsSorted 数组时,您可以使用 ...parent().get(0);将节点添加到数组而不是 jQuery 对象。

    那么在最后一次迭代之后:

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

    另外,您应该知道您尚未在 for 循环中定义变量“i”。这使它成为一个全局变量,并可能导致许多奇怪的行为。我更喜欢使用 jQuery.each,因为这也为您提供了 for 循环内的本地范围 :)

    【讨论】:

    • 太棒了。关键是我试图动态创建一个新元素并将 jQuery 对象附加到它,或者使用一个数组并弄清楚如何将元素连接在一起。我需要做的是修改原始 XML 对象文档。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2011-08-09
    相关资源
    最近更新 更多