2014-01-06 43 views
1

我想按VM字段名稱屬性對我的節點列表進行排序。 的XML:在javascript中重新排列節點列表

<SRM> 
    <HBR> 
    <VM Name="mast0010"> 
     <FieldOne>ttttt</FieldOne> 
     <Disk Name="Name One"> 
     <FieldTwo>aaaaa</FieldTwo> 
     <FieldThree>bbbbb</FieldThree> 
     </Disk> 
     <Disk Name="Name Two"> 
     <FieldTwo>fffff</FieldTwo> 
     <FieldThree>ccccc</FieldThree> 
     </Disk> 
    </VM> 
    <VM Name="mast0003"> 
     <FieldOne>rrrrr</FieldOne> 
     <Disk Name="Name One"> 
     <FieldTwo>ddddd</FieldTwo> 
     <FieldThree>eeeee</FieldThree> 
     </Disk> 
    </VM> 
    </HBR> 
</SRM> 

我寫了下面的代碼:

var x=xmlDoc.getElementsByTagName("VM");   
var ax = Array.prototype.slice.call(x, 0); 

for (var i=0; i<ax.length; i++) { 
ax.sort(function(a, b){ 
    var a = ax[i].getAttribute('Name'); 
    var b = ax[i].getAttribute('Name'); 
    if(a < b) return -1; 
    if(a > b) return 1; 
    return 0; 
    }); 
} 

for (i=0; i<ax.length; i++) { 
    document.write(ax[i].getAttribute('Name') + "<br/>"); 
} 

它返回mast0010,mast0003 我需要mast0003,mast0010秩序。請幫助我。我不明白問題出在哪裏。 THX

回答

0

請勿使用document.write,它來自JavaScript的一個古老版本,並不打算再使用。如果要將節點添加到活動文檔中,請使用parent.appendChild(node)parent.insertBefore(node)

你也調用ax.sort一百萬次(或者,對於數組中的每個元素來說,一次)。這不是你如何使用排序,所以只要把它變成一行,並依靠排序輸入,不要伸出你的數組。

改寫代碼:

ax = ax.sort(function(a,b) { 
    a = a.getAttribute("Name"); 
    b = b.getAttribute("Name"); 
    return a < b ? -1 : b < a ? 1 : 0; }); 
}); 

,然後將所得的元件到文檔的正確方法。

ax.forEach(function(node) { 
    document.body.appendChild(node); 
}); 
+0

呵呵,謝謝。它現在正在工作。 – breni

-1

Check this working demo

這裏是固定的,你的排序功能。

var x=xmlDoc.getElementsByTagName("HBR")[0].getElementsByTagName("VM");   
var ax = Array.prototype.slice.call(x, 0); 

for (var i=0; i<ax.length; i++) { 
ax.sort(function(a, b){ 
    a = a.getAttribute('Name'); 
    b = b.getAttribute('Name'); 

    if(a < b) return -1; 
    if(a > b) return 1; 
    return 0; 
    }); 
} 
+0

你可以比較字符串與< and >就好了,它根據標準字符串比較規則做了正確的事情。 –

+0

@ Mike'Pomax'Kamermans感謝您的提示。更新我的答案。 –

+0

雖然這仍然依賴於parseInt,這是沒有必要在這裏=) –