jQuery Selectors删除满足两个条件的表行

jQuery Selectors Removing table rows that meet two conditions

本文关键字:条件 两个 删除 Selectors 满足 jQuery      更新时间:2023-09-26

我试图理解当您在jQuery中有一个仅在满足多个条件时才运行的操作时采用的技术。我不知道过滤器是不是答案。

在我的示例中,一个页面上有多个表。我想删除表中满足两个条件的行。第一个条件是行不能是表的第一行(table元素的第一个子元素)。第二个条件是该行不能应用任何样式(没有声明样式元素)。我对复杂选择器的符号感到困惑。我现在要超越简单的选择器。

在我的示例中,要使用的表被标记为gvBigTable。我有以下内容:

$("#gvBigTable table tbody tr.not('style')").remove();
$("#gvBigTable table tbody tr.not(first-child)".remove();

我想结合这两个条件,以便必须同时满足这两个条件才能删除该行。任何帮助都是感激的。谢谢。

您没有正确使用:not()。你可以这样做:

$("table tbody tr:not(':first-child'):not('[style]')").remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tbody>
        <tr>
            <td>111</td>
        </tr>
        <tr>
            <td>222</td>
        </tr>
        <tr style="">
            <td>333</td>
        </tr>
        <tr>
            <td>444</td>
        </tr>
    </tbody>
</table>

UPDATE:根据David Thomas的建议,一个纯CSS解决方案如下:

table tbody tr:first-child ~ tr:not([style]) { 
    display: none; 
}
<table>
  <tbody>
    <tr>
      <td>111</td>
    </tr>
    <tr>
      <td>222</td>
    </tr>
    <tr style="">
      <td>333</td>
    </tr>
    <tr>
      <td>444</td>
    </tr>
  </tbody>
</table>

如果你不想使用display: none,那么你可以使用选择器table tbody tr:first-child ~ tr:not([style])与jQuery删除行