【问题标题】:Delete all rows in a HTML table using JavaScript使用 JavaScript 删除 HTML 表中的所有行
【发布时间】:2023-04-09 19:24:02
【问题描述】:

我的 MVC 视图中有一个 HTML 表格。

这是这个表的代码:

<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>

我需要删除表中的所有行,所以我需要删除patients中的所有内容。

我尝试通过 JS 进行如下操作,但它只删除了第一行:

<script>
    $('#search').click(function () {
        $("#patients").remove();
    });
</script>

如何删除所有行?

【问题讨论】:

  • 带有id=patients 的元素是一个&lt;tr&gt; 元素,它的html 无效,因为id 属性重复。添加具有id 属性的&lt;thead&gt;&lt;tbody&gt; 元素,并使用.empty()&lt;tbody&gt; 中删除&lt;tr&gt; 元素
  • 谢谢,它有帮助@StephenMuecke

标签: javascript jquery html dom jquery-selectors


【解决方案1】:

id 用于标识 DOM 中的唯一元素。您在 foreach 循环中错误地生成了多个具有相同 id 的元素。您可以考虑将id 更改为class。这允许识别相同类型的多个元素:

@foreach (var item in Model) {
    <tr class="patients">
        <!-- your code goes here -->
    </tr>
}

然后适当的选择器删除所有行:

$('#search').click(function () {
   $(".patients").remove();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-22
    • 2012-01-07
    • 1970-01-01
    相关资源
    最近更新 更多