使用 JavaScript 删除 HTML table 中的所有行
Delete all rows in a HTML table using JavaScript
我的 MVC 视图中有一个 HTML table。
这是table的代码:
<table class="table" >
@{int rowNo = 0;}
<tr>
<td data-toggle="modal" data-target="#newAppointment" style="height: 40px; width: 40px; background: red;">
<img style="object-fit: cover;" src='@Url.Content("~/Images/plus.png")'/>
</td>
</tr>
<tr style="background: white">
<th></th>
<th style="font-size: 20px; text-align: center;color:#1d69b4;">
Date of birth
</th>
<th style="font-size: 20px; text-align: center;color:#1d69b4;">
Last Name
</th>
<th style="font-size: 20px; text-align: center;color:#1d69b4;">
First Name
</th>
</tr>
@foreach (var item in Model)
{
<tr id="patients">
<td class="point">
@(rowNo += 1)
</td>
<td class="title">
@Html.DisplayFor(modelItem => item.Date_of_Birthday)
</td>
<td class="title">
@Html.DisplayFor(modelItem => item.Last_name)
</td>
<td class="title">
@Html.DisplayFor(modelItem => item.First_name)
</td>
</tr>
}
</table>
我需要删除 table 中的所有行,所以我需要删除 patients
中的所有行。
我尝试通过 JS 执行以下操作,但它只删除了第一行:
<script>
$('#search').click(function () {
$("#patients").remove();
});
</script>
如何删除所有行?
id 用于标识 DOM 中的唯一元素。您在 foreach
循环中错误地生成了具有相同 ID 的多个元素。您可以考虑从 id
更改为 class
。允许识别多个相同类型的元素:
@foreach (var item in Model) {
<tr class="patients">
<!-- your code goes here -->
</tr>
}
然后适当的选择器删除所有行:
$('#search').click(function () {
$(".patients").remove();
});
我的 MVC 视图中有一个 HTML table。
这是table的代码:
<table class="table" >
@{int rowNo = 0;}
<tr>
<td data-toggle="modal" data-target="#newAppointment" style="height: 40px; width: 40px; background: red;">
<img style="object-fit: cover;" src='@Url.Content("~/Images/plus.png")'/>
</td>
</tr>
<tr style="background: white">
<th></th>
<th style="font-size: 20px; text-align: center;color:#1d69b4;">
Date of birth
</th>
<th style="font-size: 20px; text-align: center;color:#1d69b4;">
Last Name
</th>
<th style="font-size: 20px; text-align: center;color:#1d69b4;">
First Name
</th>
</tr>
@foreach (var item in Model)
{
<tr id="patients">
<td class="point">
@(rowNo += 1)
</td>
<td class="title">
@Html.DisplayFor(modelItem => item.Date_of_Birthday)
</td>
<td class="title">
@Html.DisplayFor(modelItem => item.Last_name)
</td>
<td class="title">
@Html.DisplayFor(modelItem => item.First_name)
</td>
</tr>
}
</table>
我需要删除 table 中的所有行,所以我需要删除 patients
中的所有行。
我尝试通过 JS 执行以下操作,但它只删除了第一行:
<script>
$('#search').click(function () {
$("#patients").remove();
});
</script>
如何删除所有行?
id 用于标识 DOM 中的唯一元素。您在 foreach
循环中错误地生成了具有相同 ID 的多个元素。您可以考虑从 id
更改为 class
。允许识别多个相同类型的元素:
@foreach (var item in Model) {
<tr class="patients">
<!-- your code goes here -->
</tr>
}
然后适当的选择器删除所有行:
$('#search').click(function () {
$(".patients").remove();
});