javascript - 按给定的单元格值查找表行并删除该行

标签 javascript jquery html

我有一个包含 3 列的表格-

<table id="my_list">
    <thead>
    <tr>
        <th>column 1</th>
        <th>column 2</th>
        <th>column 3</th>
    </tr>
    </thead>
    <tr>
        <td>value 1</td>
        <td>value 2</td>
        <td>value 3</td>
    </tr>
</table>

我正在编写一个函数,用于在表中搜索 given_value 并删除包含它的行-

function delete_row (given_value) {
    var table_row = $("td").filter(function() {
        return $('#my_list').text() == given_value;
    }).closest("tr");

    // Removing the row from `my_list` table
    table_row.remove();

}

但这并不是删除行。

此外,我只想搜索 第 2 列 中的文本值,所以如果有更快的方法来搜索表格,那也很好。

最佳答案

我认为这就是您要查找的内容,但您可以遍历 td 元素并检查其文本,如果找到匹配项,则删除 tr 元素.

编辑:如果你想指定一个 id,你可以像这样将它添加到函数中。然后只需为函数提供 id 名称和要查找的值。

function delete_row(id, given_value) {
  var td = $("#" + id + " td");
  $.each(td, function(i) {
    if ($(td[i]).text() === given_value) {
      $(td[i]).parent().remove();
    } 
  });
}

delete_row('my_list', 'value 1');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="my_list">
  <thead>
  <tr>
    <th>column 1</th>
    <th>column 2</th>
    <th>column 3</th>
  </tr>
  </thead>
  <tr>
    <td>value 1</td>
    <td>value 2</td>
    <td>value 3</td>
  </tr>
</table>

关于javascript - 按给定的单元格值查找表行并删除该行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57150077/

相关文章:

jquery - 显示 :none and inline-block at the same time

javascript - 带有运行页眉和页脚的打印页面中的动态内容

"calendar"的 HTML 表格 CSS 设计

javascript - Unix 偏移与 fullCalendar 差异

javascript - 有趣的 Javascript RegExp 测试

javascript - 摆脱 Javascript 中的拒绝 promise 递归

javascript - 更改 Javascript cookies 重定向

javascript - 在图像顶部动态添加元素

javascript - switch 语句中有 html 和变量

php - 选项选择的默认设置