2011-05-09 152 views
0

我試圖在JavaScript中的遞歸函數應該基本上給我HTML像下面使用JavaScript遞歸函數不工作

<li><a class="expand">+</a> <span class="treeNodeInner"><a id="7471">Ringtones</a> 
      <ul> 
       <li><span class="treeNodeInner"><a id="7995">Top Tones</a></span></li> 
       <li><span class="treeNodeInner"><a id="8642">Country</a></span></li> 
       <li><span class="treeNodeInner"><a id="8640">Rock</a></span></li> 
      </ul> 
     </span></li> 

我使用下面的功能,使使用javascript上面的HTML創建HTML。 它基本上是一個樹視圖,我們將有節點和子節點的東西。

我奮力的實現通過以下功能上面的HTML結構,請與下面的功能建議修改

function GenerateNodes(categItem) { 
    var parentNode = "<li>"; //parent li 
    if (categItem.SubCategory != null && categItem.SubCategory != undefined && categItem.SubCategory.Count > 0) { 
     parentNode = "<li><a class='expand'>+</a>"; 
    } 
    parentNode += "<input type='radio' name='category' /><span class='treeNodeInner'><a id='" + categItem.ID + "'>" + categItem.name + "</a> "; //need to close the span 

    if (categItem.SubCategory != null && categItem.SubCategory != undefined && categItem.SubCategory.Count > 0) { 
     var subNode = "<span><ul>"; 
     for (var index = 0; index < categItem.SubCategory.Count; index++) { 
      subNode += GenerateNodes(categItem.SubCategory[index]); 
      subNode += "</ul></span>" 
     } 
     parentNode += subNode 
    } 
     parentNode += "</span></li>" 
} 

感謝

+0

你還是不在你的代碼中使用jQuery?我沒有在您的示例中看到jQuery功能的單一引用。 – 2011-05-09 09:40:24

+0

好吧,我現在沒有使用任何jquery,但如果有人可以告訴我,我會用它 – Amit 2011-05-09 09:41:55

+0

而不是'categItem.SubCategory!= null && categItem.SubCategory!= undefined'你可以只有'catagItem.SubCategory'如果它是'null'或'undefined',它將評估爲'false'。 – geekchic 2011-05-09 09:42:22

回答

1

睜眼看代碼,我發現你不插入新的li在你的HTML。我不確定你是否在你的代碼之外管理這個地方。我複製了你的代碼並對它進行了一些調試。然後我嘗試使用一些代碼在html上添加li。請參見下面的代碼:

//Insert this after parentNode += "</span></li>"; 
var newDiv = document.createElement('div'); 
newDiv.innerHTML = parentNode; 
categItem.appendChild(newDiv.childNodes[0]); 

//I assume that categItem is the id of the container as your sample html code 
//above is not clear to me. So I did using sample html below 
<div id="liContainer"> 
</div>  

看到這個jsfiddle如何上面的代碼工作。我知道這不完全是你想要的,但我希望你能從中得到一些想法。