简体   繁体   English

jQuery-如果在表tr中有4 td做某事

[英]jQuery - if in table tr there is 4 td do something

I'm trying to remove any tr from table that has less than 4 td inside. 我正在尝试从内部小于4 td的 中删除所有tr

So for example, in this table I want second tr to go away: 因此,例如,在此表中,我希望第二个tr消失:

HTML 的HTML

<table>
  <tbdy>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
    </tr>
  </tbody>
</table>

I'm trying with something like this 我正在尝试这样的事情

jQuery jQuery的

if ($('table tbody tr td').length >= 4) {
  //4 i ok so do nothing
} else {
  $(this).parent("tr").remove();
}

But I getting nowhere with this. 但是我对此一无所知。 Any help? 有什么帮助吗?

Use jQuery :has() selector with :not() and :nth-child() pseudo-class selector. 将jQuery :has()选择器与:not():nth-child()伪类选择器一起使用。

 $('tr:not(:has(:nth-child(4)))').remove() 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tbody> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> </tr> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> </tbody> </table> 


Or alternatively, use filter() method to filter out element only contains td less than 4 and remove. 或者,使用filter()方法过滤掉仅包含td小于4的元素并删除。

 $('tr').filter(function() { return $(this).children('td').length < 4; }).remove() 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tbody> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> </tr> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> </tbody> </table> 

This should work: 这应该工作:

$('table tbody tr').each(function() {
    var $tr = $(this);
    if ($tr.find('> td').length < 4) {
        $tr.remove();
    }
});

Your structure should be : 您的结构应为:

 <table>
  <tbody>
    <tr>

And you can select it with : 您可以选择:

$('table tbody tr')

To get all tr with less than 4 columns you should loop through them. 要获得少于4列的所有tr,您应该遍历它们。

Your final code should be : 您的最终代码应为:

$('table tbody tr').each(function() {
    var row = $(this);
    if (row.find('td').length < 4) {
        row.remove();
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM