2012-02-14 88 views
2

我试图开发一个JS函数,每次将新记录添加到数据库(从定期检查的其他程序中)创建一个新行。现在我可以得到函数来检查数据库,将记录添加到表中并动态显示它。第一列是用户标识,第二列是我遇到问题的地方。我想包括一个下拉菜单,但我不确定如何添加选项。我在第二列中有下拉列表,但没有可供选择的选项。任何人都有一些建议?动态创建下拉列表 - JavaScript

function addRow(tableID, user) { 

var table = document.getElementById(tableID); 

var rowCount = table.rows.length; 
var row = table.insertRow(rowCount); 

var colCount = table.rows[0].cells.length; 

for(var i=0; i<colCount; i++) { 
    var opt = document.createElement("option"); 

    tabbody=document.getElementsByTagName("tbody").item(2); 
    cell1 = document.createElement("TD"); 
    cell2 = document.createElement("TD"); 
    textnode1=document.createTextNode(user); 
    //textnode2=document.createTextNode("morecontent"); 
    textnode2=document.createElement("select"); 
    textnode2.setAttribute('id', 'focus'); 
    textnode2.options.add(opt); 
    cell1.appendChild(textnode1); 
    cell2.appendChild(textnode2); 
    row.appendChild(cell1); 
    row.appendChild(cell2); 
    tabbody.appendChild(row); 

    var newcell = row.insertCell(i); 

    newcell.innerHTML = table.rows[0].cells[i].innerHTML; 

这是它被发送到HTML:

 <th colspan="2">Pending Alerts</th> 
    <tr> 
     <th>User</th> 
     <th>Action</th> 
     </tr> 
    <tbody> 
    </tbody> 

回答

5

textnode2 = document.createElement("select"); 

你需要做的是这样

var op = new Option(); 
op.value = 1; 
op.text = "First entry"; 
textnode2.options.add(op);  

,并重复你想要的条目。

+0

如何定义option()?我得到一个错误,说“ReferenceError:选项未定义” – mkyong 2012-02-14 11:44:37

+1

没关系。我知道了。我不得不将'new option()'改成'document.createElement(“option”);'谢谢你的帮助! – mkyong 2012-02-14 11:47:01

+1

本应该是'Option()' - 大写字母O – 2012-02-14 11:49:44

3

我喜欢这种方法。

var dropdown = document.getElementById("MyDropDownList"); 
var opt = document.createElement("option"); 
opt.text = 'something'; 
opt.value = 'somethings value'; 
dropdown.options.add(opt);