动态地在 HTML 表格中添加/删除行

10

我正在开发一个表格,可以通过按下每行的“删除”按钮来修改表格,并通过“插入行”在末尾添加新行:

到目前为止,我的代码如下:

<!DOCTYPE html>
<html>
<head>
<script>
function deleteRow(id,row) {
    document.getElementById(id).deleteRow(row);
}

function insRow(id) {
    var filas = document.getElementById("myTable").rows.length;
    var x = document.getElementById(id).insertRow(filas);
    var y = x.insertCell(0);
    var z = x.insertCell(1);
    y.innerHTML = '<input type="text" id="fname">';
    z.innerHTML ='<button id="btn" name="btn" > Delete</button>';
}
</script>
</head>
<body>

<table id="myTable" style="border: 1px solid black">
<tr>
  <td><input type="text" id="fname"></td>
  <td><input type="button" value="Delete" onclick="deleteRow('myTable',0)"></td>
</tr>
<tr>
  <td><input type="text" id="fname"></td>
  <td><input type="button" value="Delete" onclick="deleteRow('myTable',1)"></td>
</tr>
<tr>
  <td><input type="text" id="fname"></td>
  <td><input type="button" value="Delete" onclick="deleteRow('myTable',2)"></td>
</tr>
</table>
  
 <p>
<input type="button" onclick="insRow('myTable')" value="Insert row">
</p>
</body>
</html>

但我无法将onclick="deleteRow('myTable',0)"函数附加在上面。

z.innerHTML ='<button id="btn" name="btn"> Delete</button>'

当点击按钮时,我是否需要声明其他内容才能使其正常工作?

谢谢你的回答。

4个回答

18

首先,ID必须是唯一的,那么为什么不在这里使用类呢?

其次,如果你正在使用jQuery,则应该使用jQuery。

第三,在动态添加元素时需要使用事件委托,因此请尝试以下操作:

$('#myTable').on('click', 'input[type="button"]', function () {
    $(this).closest('tr').remove();
})
$('p input[type="button"]').click(function () {
    $('#myTable').append('<tr><td><input type="text" class="fname" /></td><td><input type="button" value="Delete" /></td></tr>')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="myTable" style="border: 1px solid black">
    <tr>
        <td>
            <input type="text" class="fname" />
        </td>
        <td>
            <input type="button" value="Delete" />
        </td>
    </tr>
    <tr>
        <td>
            <input type="text" class="fname" />
        </td>
        <td>
            <input type="button" value="Delete" />
        </td>
    </tr>
    <tr>
        <td>
            <input type="text" class="fname" />
        </td>
        <td>
            <input type="button" value="Delete" />
        </td>
    </tr>
</table>
<p>
    <input type="button" value="Insert row">
</p>


谢谢。我一直在寻找一种避免使用JavaScript部分的方法,因为我正在使用Google应用服务,但我发现如果将第一部分放在第二部分的末尾,并用<script> </script>包围起来,代码就可以正常工作! - David Menacho

2
在每个DeleteRow(tableId,Index)函数中,您都会传递表格id和静态索引,因此document.getElementById("mytable").deleteRow(Index)首先查找表节点,然后查找tr元素的子元素数量,并将索引分配给从0开始的tr元素,然后删除匹配索引的tr元素。
当您删除第一行时,它将从3个元素中匹配0索引并删除第一行。现在剩下2个tr,索引为0和1,由表动态分配,但您尝试与1和2匹配。
要删除第二行,它将删除索引为1(第三个tr)而不是第二个tr。
要删除第三行,实际索引为0(删除2行后),而您正在传递1,因此它无法找到匹配的索引。
这里是一个简单的JavaScript解决方案。
<script>

function delRow(currElement) {
     var parentRowIndex = currElement.parentNode.parentNode.rowIndex;
     document.getElementById("myTable").deleteRow(parentRowIndex);
}

</script>

and html,

<table id="myTable" style="border: 1px solid black">
<tr>
  <td><input type="text" id="fname"></td>
  <td><input type="button" value="Delete" onclick="delRow(this)"></td>
</tr>
<tr>
  <td><input type="text" id="fname"></td>
  <td><input type="button" value="Delete" onclick="delRow(this)"></td>
</tr>
<tr>
  <td><input type="text" id="fname"></td>
  <td><input type="button" value="Delete" onclick="delRow(this)"></td>
</tr>
</table>

这里是一个 JSFiddle 示例

点击此处


2

假设您有以下表格:

<table id="myTable">
                <thead>
                    <tr>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Email</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><input type="text" name="firstName" /></td>

                        <td><input type="text" name="lastName" /></td>

                        <td> <input type="text" name="email" /></td>                            
                    </tr>                       
                </tbody>
                <p>
                    <label>Insert</label>
                    <input type="number" value="1" id="numberOfRowsToInsert">
                    <input type="button" value="Insert row" id="insert-line-button">
                </p>
</table>

以下jQuery代码将生成用户输入的x行,并将它们附加到表格底部,如果需要,可以删除它们:
$('#insert-line-button').on("click", function(){
    var noOfRows = $('#numberOfRowsToInsert').val();
    for(var i = 0; i < noOfRows; i++){
        $('#myTable').append("<tr>" +
                "<td><input type='text' name='firstName' /></td>" +
                "<td><input type='text' name='lastName' /></td>" +
                "<td> <input type='text' name='email' /></td>" +
                "<td><input type='button' value='Delete' id='deleteRowButton' /></td>" +
                "</tr>")        
    }

});

以下 jQuery 代码将在单击“删除”按钮时删除行:
$("#myTable").on('click', 'input[id="deleteRowButton"]', function(event) {
    $(this).parent().parent().remove();
});

0
Go through below code:
You can see that this is the most basic way to create dynamic table. You can use this approach and can try yourself to remove rows from the existing table. I have not used any pluggin/ jquery. You can just copy this code and save as an html file to see how this code is working. Go head! Good luck.


    <html>
        <script>
        function CreateTableAndRows(){
            var mybody = document.getElementsByTagName("body")[0];
            var newTable = document.createElement("table"); 
            var newTableHead = document.createElement("thead");
            var headRow = document.createElement("tr");     
            var headHead1 = document.createElement("th");
            var headRowCellValue = document.createTextNode("Device Name");
            headHead1.appendChild(headRowCellValue);
            var headHead2 = document.createElement("th");   
            headRowCellValue = document.createTextNode("Start Timing");
            headHead2.appendChild(headRowCellValue);
            var headHead3 = document.createElement("th");   
            headRowCellValue = document.createTextNode("End Timing");
            headHead3.appendChild(headRowCellValue);
            var headHead4 = document.createElement("th");   
            headRowCellValue = document.createTextNode("Duration");
            headHead4.appendChild(headRowCellValue);
            headRow.appendChild(headHead1);
            headRow.appendChild(headHead2);
            headRow.appendChild(headHead3);
            headRow.appendChild(headHead4);
            newTableHead.appendChild(headRow);
            newTable.appendChild(newTableHead);     
            var newTableBody = document.createElement("tbody");
            for(var rowCount=0;rowCount<5;rowCount++)
            {
                var newTableRow = document.createElement("tr");         
                for(var cellCount=0; cellCount<4; cellCount++)
                {
                    var newTableRowCell = document.createElement("td");
                    var cellValue = document.createTextNode("cell is row"+rowCount+", coumn "+cellCount);
                    newTableRowCell.appendChild(cellValue);
                    newTableRow.appendChild(newTableRowCell);
                }
                newTableBody.appendChild(newTableRow);
            }
            newTable.appendChild(newTableBody);
            newTable.setAttribute("border","2");
            mybody.appendChild(newTable);
        }    
   </script>
   </head>
   <body>
    <input type="submit" onclick="CreateTableAndRows();">
   </body>
  </html>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接