删除html表格行最后一个单元格的内容

时间:2018-07-25 12:17:01

标签: javascript html

我有一个包含行的html表:

<tr id="firstInRow"><td></td><td><input name="longP1" id="longP1" type="text" style="width: 70px"></td><td><input name="latP1" id="latP1" type="text" style="width: 70px"></td><td>(upper left)</td></tr>
<tr id="secInRow"><td></td><td><input name="longP2" id="longP2" type="text" style="width: 70px"></td><td><input name="latP2" id="latP2" type="text" style="width: 70px"></td><td>(lower right)</td></tr>

会创建一个像这样的表: latLongTable

我已经创建了一个行添加功能,并且正在尝试删除该功能中最后一个单元格的内容。我要删除文本“(左上)”和“(右下)”。我尝试了几种方法,包括:

var rowIn1 = document.getElementById("firstInRow");
rowIn1.deleteCell(-1);

但这不起作用。

1 个答案:

答案 0 :(得分:2)

您可以使用jQuery的.remove()函数。 例如:

$("#firstInRow").find("td:last-child").remove();

这将找到ID为 firstInRow 的行的最后一列(td),并将其从DOM中删除。您可以使用相同的方法删除其他单元格。

如果只想删除内容,请使用:

$("#firstInRow").find("td:last-child").text('');

这不会从DOM中删除最后一列,而是会清除最后一列中的内容。

$("#clear").on("click", function() {
$("#firstInRow").find("td:last").text("");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<table border="1" cellpadding="5">
<tr id="firstInRow">
<td>First</td>
<td>Last</td>
<td>Content to clear</td>
</tr>
</table>
<button type="button" id="clear">Clear last column</button>
</body>

相关问题