从表格中删除单元格

时间:2020-08-19 16:54:58

标签: html jquery

我有上面的示例,但是当我尝试删除像Cell C一样的问题时,它会删除所有的cells

我想删除一些tr并留下一些。并非全部

$(document).ready(function() {
  $("button").click(function() {
    $("td").remove();
  });
});
<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<body>

  <table>
    <tr>
      <td>Cell A <button>Remove Cell A</button></td>
    </tr>
    <tr>
      <td>Cell B <button>Remove Cell B</button></td>
    </tr>
    <tr>
      <td>Cell C <button>Remove Cell C</button></td>
    </tr>
    <tr>
      <td>Cell D <button>Remove Cell D</button></td>
    </tr>
  </table>
</body>

</html>

1 个答案:

答案 0 :(得分:1)

使用$("td")时,您会发现它选择了页面上的所有td单元。

您需要将其定位为仅与按下按钮相关的对象。在按钮jquery-click处理程序中,被按下的按钮定义为this,可用于查找与按钮相关的单元格。

.closest合并以获取与按钮相关的单元格:

$(this).closest("td")

给予:

$(document).ready(function() {
  $("button").click(function() {
    $(this).closest("td").remove();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Cell A <button>Remove Cell A</button></td>
  </tr>
  <tr>
    <td>Cell B <button>Remove Cell B</button></td>
  </tr>
  <tr>
    <td>Cell C <button>Remove Cell C</button></td>
  </tr>
  <tr>
    <td>Cell D <button>Remove Cell D</button></td>
  </tr>
</table>

如果您要删除整行(例如,如果按钮位于不同的列/ td中),则可以将.closest("td")更改为.closest("tr")

相关问题