2016-03-01 53 views
2

我收到了有关删除表格内表格行的问题。我得到了以下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的事实。

我该如何做到这一点?

+1

'$('TR:不(:has(.html5badge))')。remove();' - https://jsfiddle.net/fe9o3wf0/ – billyonecan

回答

3

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

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

Updated fiddle

+0

太棒了!从未使用过滤功能。似乎正是我想要的! – Rotan075

+0

没问题,很高兴帮助。过滤功能是一个很好用的工具,功能非常强大:http://api.jquery.com/filter –

1

只是让它

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