在下面的代码我有html表,我需要在html表中添加行并插入数据库。但是我无法添加row.Pls帮助我纠正问题。我的目标是避免回发所以我选择javascript添加行。
<script language="javascript">
function addRow(tableID) {
var table = document.getElementById("<%=dataTable.ClientID%>").value;
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 newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
switch (newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById("<%=dataTable.ClientID%>");
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked) {
if (rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
alert(e);
}
}
</script>
<input type="button" value="Add Row" onclick="addRow('dataTable')"/>
<input type="button" value="Delete Row" onclick="deleteRow('dataTable')"/>
<table id="dataTable" width="350px" border="1" runat="server">
<tr>
<td><input type="checkbox" name="chk" runat="server"/></td>
<td><input type="text" name="txt" runat="server"/></td>
<td>
<asp:DropDownList ID="ddlProduct" runat="server" OnSelectedIndexChanged="ddlProduct_SelectedIndexChanged" AutoPostBack="true" Style="width: 100%; height:23px" ></asp:DropDownList>
</td>
</tr>
</table>
答案 0 :(得分:0)
这些行是问题所在:
var table = document.getElementById("<%=dataTable.ClientID%>").value;
var row = table.insertRow(rowCount);
纠正他们:
var tableBody = document.getElementById("<%=dataTable.ClientID%>").getElementsByTagName("tbody")[0];
var row = tableBody .insertRow(rowCount);
行插入tablebody
(tbody
)和/或tablehead
(thead
)。
var table = document.getElementById("<%=dataTable.ClientID%>").value
将返回undefined
。 value属性仅用于输入以检索或设置输入的内容。