动态创建Dropdown-Javascript

Creating Dropdown Dynamically - Javascript

本文关键字:Dropdown-Javascript 创建 动态      更新时间:2023-09-26

我正在尝试开发一个JS函数,该函数在每次向数据库添加新记录时创建一个新行(来自定期检查的不同程序)。现在,我可以获得检查数据库、将记录添加到表中并动态显示它的函数。第一列是用户id,第二列是我遇到问题的地方。我想包括一个下拉列表,但我不知道如何添加选项。我在第二列中有下拉列表,但是没有选项可供选择。有人有什么建议吗?

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>

之后

textnode2 = document.createElement("select");

你需要做一些类似的事情

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

并为您想要的条目重复。

我喜欢这个方法。

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