如何使用 javascript 在表中动态插入带有选项的选择框的表行

How to dynamically insert a table row with a select box with options in a table using javascript?

本文关键字:选项 选择 插入 javascript 何使用 动态      更新时间:2023-09-26

我很难动态插入表行,因为我以前没有真正尝试过。我应该做的是插入一个新的表行,其中包含一个选择框,其中包含数组列表中的选项。

到目前为止,这是我的代码:

.HTML

<TABLE id="dataTable">         
    <TR>             
        <TD> 1</TD>             
        <TD> 
            <select name="option">
            <%for(int i = 0; i < jList.size(); i ++){%>
            <option value="<%=jList.get(i).getName%>"><%=jList.get(i).getName%></option>
            <%}%>
            </select>
        </TD>         
    </TR>     
    </TABLE> 
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />  

JAVASCRIPT

function addRow(tableID) {               
    var table = document.getElementById(tableID);               
    var rowCount = table.rows.length;         
    var count = rowCount + 1;
    var row = table.insertRow(rowCount);               
         //*** EDIT ***               
    var cell1 = row.insertCell(0);             
    cell1.innerHTML = count;
    var cell2 = row.insertCell(1);             
    var element2 = document.createElement("select");   
//how do i put the options from the arraylist here?
    cell2.appendChild(element2);  

}

另外,我还想知道如何将变量从javascript函数传递给java servlet,因为每次我在隐藏的输入类型中传递变量计数时,输入都不包含计数。我希望你能帮助我解决我的困境。

在创建"选择"元素之后,您可以简单地遍历您的"arraylist"并附加选项:

function addRow(tableID) {               
    var table = document.getElementById(tableID);               
    var rowCount = table.rows.length;         
    var count = rowCount + 1;
    var row = table.insertRow(rowCount);               
        //*** EDIT ***               
    var cell1 = row.insertCell(0);             
    cell1.innerHTML = count;
    var cell2 = row.insertCell(1);             
    var element2 = document.createElement("select");
    //Append the options from the arraylist to the "select" element
    for (var i = 0; i < arraylist.length; i++) {
        var option = document.createElement("option");
        option.value = arraylist[i];
        option.text = arraylist[i];
        element2.appendChild(option);
    }
    cell2.appendChild(element2);  
} 

看看这个小提琴:https://jsfiddle.net/bafforosso/66h3uwtd/2/