2010-05-29 50 views
0

我有一個方法試圖在列表中。該列表可以包含數據和其他列表。最終的目標是嘗試的東西轉換成這樣使用Javascript遞歸生成嵌套列表時獲取HIERARCHY_REQUEST_ERR

["a", "b", ["c", "d"]] 

<ol> 
    <li> 
     <b>a</b> 
    </li> 
    <li> 
     <b>b</b> 
    </li> 
    <ol> 
     <li> 
      <b>c</b> 
     </li> 
     <li> 
      <b>d</b> 
     </li> 
    </ol> 
</ol> 

的代碼是:

function $(tagName) { 
    return document.createElement(tagName); 
} 

//returns an html element representing data 
//data should be an array or some sort of value 
function tagMaker(data) { 
    tag = null; 


    if(data instanceof Array) { 
     //data is an array, represent using <ol> 
     tag = $("ol"); 
     for(i=0; i<data.length; i++) { 
      //construct one <li> for each item in the array 
      listItem = $("li"); 
      //get the html element representing this particular item in the array 
      child = tagMaker(data[i]); 
      //<li>*html for child*</li> 
      listItem.appendChild(child); 
      //add this item to the list 
      tag.appendChild(listItem); 
     } 
    } else { 
     //data is not an array, represent using <b>data</b> 
     tag = $("b"); 
     tag.innerHTML = data.toString(); 
    } 

    return tag; 
} 

調用tagMaker拋出HIERARCHY_REQUEST_ERR:DOM異常3,而不是產生我打算附加到document.body的有用的HTML元素對象。

回答

1

我想通了。在函數中,如果在創建新變量時不使用var關鍵字,那麼JavaScript將爲變量提供全局範圍。當我試圖遞歸生成新標籤時,它覆蓋了父標籤。錯誤出現是因爲我試圖向自己添加一個元素。一個工作版本出現在下面。

function $(tagName) { 
    return document.createElement(tagName); 
} 

//returns an html element representing data 
//data should be an array or some sort of value 
function tagMaker(data) { 
    var tag = null; 


    if(data instanceof Array) { 
     //data is an array, represent using <ol> 
     tag = $("ol"); 
     for(var i=0; i<data.length; i++) { 
      //construct one <li> for each item in the array 
      var listItem = $("li"); 
      //get the html element representing this particular item in the array 
      var child = tagMaker(data[i]); 
      //<li>*html for child*</li> 
      listItem.appendChild(child); 
      //add this item to the list 
      tag.appendChild(listItem); 
     } 
    } else { 
     //data is not an array, represent using <b>data</b> 
     tag = $("b"); 
     tag.innerHTML = data.toString(); 
    } 

    return tag; 
}