2013-04-28 75 views
0

我想使用一個按鈕將選擇列表添加到我的網站。 我需要使用節點,因爲我需要能夠在DOM中訪問它,所以我可以稍後檢索它的值,所以我不能使用innerHTML。createTextNode圍繞我的選擇列表不需要的引號

我的問題是,createTextNode似乎圍繞我的列表引號,所以它不會顯示。誰能幫我出

<!doctype html> 
<html> 
<head> 
    <title> Pop Up </title> 

<script> 
function change() 
{ 
    var theDiv = document.getElementById("dropDownList"); 
    var content = document.createTextNode("<select name='scrapbookID' id='scrapbookID'><option value='15'>one</option><option value='18'>two</option><option value='20'>three</option><option value='21'>four</option></select>"); 

    theDiv.appendChild(content); 
} 
</script> 

<style type = "text/css"> 


</style> 


</head> 
<body> 

    <div id = "signout"> 
     Your are Currently signed in.<br /> 
     <a href = "#" id = "signOutPHP">Sign Out</a> 
     <div id = "dropDownList"> 
      <button onclick="change()">Add List</button> 

     </div> 
    </div> 

</body> 

回答

1

你需要有什麼是.createElement()它創建了一個給定的元素,其中作爲createTextNode與給定的內容創建文本節點。

function change() 
{ 
    var theDiv = document.getElementById("dropDownList"); 

    var select = document.createElement('select'); 
    select.name = 'scrapbookID'; 
    select.id = 'scrapbookID'; 
    select.innerHTML = "<option value='15'>one</option><option value='18'>two</option><option value='20'>three</option><option value='21'>four</option>" 

    theDiv.appendChild(select); 
} 

演示:Fiddle

1

當你創建一個文本節點,它被視爲正是:文本,而不是HTML。但是,正確地構建DOM更簡潔!

function change() { 
    var theDiv = document.getElementById("dropDownList"); 

    var selectBox = document.createElement("select"); 
    selectBox.id = "scrapbookID"; 
    selectBox.name = "scrapbookID"; 

    var options = { 
     "15": "one", 
     "18": "two", 
     "20": "three", 
     "21": "four" 
    }; 

    for(var x in options) { 
     if(options.hasOwnProperty(x)) { 
      var option = document.createElement("option"); 
      option.value = x; 
      option.appendChild(document.createTextNode(options[x])); 

      selectBox.appendChild(option); 
     } 
    } 

    theDiv.appendChild(selectBox); 
}