2017-02-13 49 views
0

我有一個jQuery遞歸函數,它解析我的xml數據,但我試圖選擇子元素的子元素,所以基本上元素內的元素。例如在xml中我想選擇<to>標籤,所以我可以縮進並添加一個展開摺疊按鈕。jQuery遞歸函數select children

XML

<?xml version="1.0" encoding="UTF-8"?> 
<note> 
    <to>Tove</to> 
    <from>Jani</from> 
    <heading>Reminder</heading> 
    <body>Don't forget me this weekend!</body> 
</note> 

jQuery的

function traverse(tree) { 
      $(tree).contents().each(function (i, child) { 
        if (child.nodeType == 3) { // text node 

         $("#xml-reader").append(
          '<span>' + child.nodeValue + '</span>' 
         ); 

         // this is my attempt 
         if (child.children) { // element node 
          $("#xml-reader").append(
           '<br><i>' + child.nodeName + ": " + '</i>' 
          ); 
         } 
        } else { 
         if (child.nodeType === 8) { // comment node 

          $("#xml-reader").append(
           '<i>' + child.nodeValue + '</i>' 
          ); 
         } 
         else { 
          $("#xml-reader").append(
           '<br><b>' + child.nodeName + ": " + '<b>' 
          ); 
          traverse(child); 
         } 
        } 
       } 
      ); 
     } 

     traverse($(xml).find('*')); 
+1

'當你要訪問一個節點的孩子,那麼它應該是一個函數child.children':'child.children ()'。如果child是一個包含節點的對象,那麼你可以通過'child.to'來訪問它。爲了驗證你能設置一個例子,還是在'.each()'裏面指定'tree'或'child'的內容? – empiric

+0

@empiric我重寫了整個功能。我現在有一個遞歸函數,它將解析任何xml文件並將其作爲可擴展樹在瀏覽器中輸出。 – theWhiteFox

回答