到目前爲止,我已經閱讀了很多文章,並嘗試了很多不同的方式來動態地向我的HTML表格添加行,但沒有任何工作。當我點擊添加按鈕[+]時,它不會添加一行。出於某種原因,看起來它不會讓我添加單元格,當我這樣做時:newCell = newRow.insertCell()
。我的newRow
變量找不到insertCell()
方法。爲什麼我無法將行動態添加到我的HTML表格中?
這是我的表:
<table ID="newDataTable" runat="server" width="400">
<tr runat="server">
<td runat="server" nowrap="nowrap" bordercolor="#FFFFFF" width= "50">
<label style="font-size:smaller"> CITY: </label>
</td>
<td runat="server" nowrap="nowrap" bordercolor="#FFFFFF" width= "80">
<input id= "City_box" type="text" name="tb_CITY"/>
</td>
<td runat="server" nowrap="nowrap" bordercolor="#FFFFFF" width= "75">
<label style="font-size:smaller"> STATE: </label>
</td>
<td runat="server" nowrap="nowrap" bordercolor="#FFFFFF" width= "90">
<input id= "State_box" type="text" name="tb_STATE"/>
</td>
<td runat="server" align="left" bordercolor="#FFFFFF" width= "10">
<input title="Add Row" id="addButton" type="button" value=" + " onclick="addRow()" />
</td>
<td runat="server" align="left" bordercolor="#FFFFFF" width= "10">
<input title="Remove Row" id="deleteButton" type="button" value=" - " onclick="removeRow(this)" />
</td>
</tr>
</table>
這裏是我使用的Javascript:
<script type="text/javascript">
//add a new row to the table
function addRow()
{
//add a row to the rows collection and get a reference to the newly added row
var newRow = document.getElementById('newDataTable').insertRow(-1);
//add 3 cells (<td>) to the new row and set the innerHTML to contain text boxes
var newCell = newRow.insertCell();
newCell.innerHTML = "<label style='font-size:smaller'> CITY: </label>";
newCell = newRow.insertCell();
newCell.innerHTML = "<input type='text' name='tb_CITY'/>";
newCell = newRow.insertCell();
newCell.innerHTML = "<label style='font-size:smaller'> STATE: </label>";
newCell = newRow.insertCell();
newCell.innerHTML = "<input type='text' name='tb_STATE'/>";
newCell = newRow.insertCell();
newCell.innerHTML = "<input title='Add Row' name='addButton' type='button' value=' + ' onclick='addRow()' />";
newCell = newRow.insertCell();
newCell.innerHTML = "<input title='Remove Row' name='deleteButton' type='button' value=' - ' onclick='removeRow(this)' />";
}
//deletes the specified row from the table
function removeRow(src)
{
/* src refers to the input button that was clicked.
to get a reference to the containing <tr> element,
get the parent of the parent (in this case <tr>)
*/
var oRow = src.parentElement.parentElement;
//once the row reference is obtained; delete it passing in its rowIndex
document.all("newDataTable").deleteRow(oRow.rowIndex);
}
</script>
你的Js小提琴在IE中工作,但不是Firefox,但當添加Jonathan M的答案時,它修復了它。只是覺得值得注意 – Chris
@Chris謝謝。我更新了我的答案。 – ThinkingStiff
謝謝大家的幫助!這個愚蠢的小錯誤導致我差不多一天:/ – AlwaysANovice