如果表数据不包含特定类,则删除表行

Delete table rows if table data does not contain a specific class

本文关键字:删除 数据 包含特 如果      更新时间:2023-09-26

>我有一个关于删除表中的表行的问题。我得到了以下 HTML:

<table>
      <tr>
          <td class="html5badge"><a href="">autofocus</a></td>
          <td>autofocus</td>
          <td>Specifies that the drop-down list should automatically get focus when the page loads</td>
      </tr>
      <tr>
          <td><a href="">disabled</a></td>
          <td>disabled</td>
          <td>Specifies that a drop-down list should be disabled</td>
      </tr>
      <tr>
          <td class="html5badge"><a href="">test</a></td>
          <td>autofocus</td>
          <td>Specifies that the drop-down list should automatically get focus when the page loads</td>
      </tr>
</table>

我需要一种机制来查看第一个<td>是否不包含html5badge类并删除父级:<tr>

为此,我创建了以下jQuery代码:

$(document).ready(function() {
    $(".onlyhtml5").click(function(event) {
        event.preventDefault();
        var classname = $('table tr td').not('.html5badge'); 
        console.log(classname)
        for (i = 0; i < classname.length; i++) { 
                $(classname[i].parentNode).remove();    
        }                
    });
});

这有效,但它并不完全是我想要的。正如您在我的 JSFIDDLE 中看到的,它将删除所有表行。但我想要的是以下所需的输出:

<table>
      <tr>
          <td class="html5badge"><a href="">autofocus</a></td>
          <td>autofocus</td>
          <td>Specifies that the drop-down list should automatically get focus when the page loads</td>
      </tr>
      <tr>
          <td class="html5badge"><a href="">test</a></td>
          <td>autofocus</td>
          <td>Specifies that the drop-down list should automatically get focus when the page loads</td>
      </tr>
</table>

所需的输出是删除包含文本:禁用的<tr>!基于此<tr>中的<td>不包含类的事实:html5badge .

我怎样才能做到这一点?

您可以使用filter()来检索不包含td.html5badgetr元素并将其删除:

$(".onlyhtml5").click(function(e) {
    e.preventDefault();
    $('tr').filter(function() {
        return $(this).find('td.html5badge').length == 0;
    }).remove();
});

更新的小提琴

只需制作即可

$(document).ready(function() {
    $(".onlyhtml5").click(function(event) {
        event.preventDefault();
        $('table tr td').not('.html5badge').each( funtion(){
           $( this ).parent().remove();
        } ); 
    });
});