我很难动态插入表行,因为我之前没有真正尝试过。我应该做的是插入一个带有选择框的新表行,其中包含来自arraylist的选项。
到目前为止,这是我的代码:
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,因为每次我在隐藏输入类型中传递变量count时,输入都不包含计数。我希望你能帮我解决我的困境。
答案 0 :(得分:1)
创建“select”元素之后您可以简单地遍历“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);
}
Take a look at this fiddle:https://jsfiddle.net/bafforosso/66h3uwtd/2/