【问题标题】:Selecting TD inside a table在表格中选择 TD
【发布时间】:2017-08-12 23:40:50
【问题描述】:

在jQuery中,如何选择所有内部只有2个TD的TR? 这是示例:

<table>
   <tr>
      <td></td>
   </tr>          
   <tr> /* I only want to select this. */
      <td></td>
      <td></td>
   </tr>
   <tr>
      <td></td>
   </tr>
</table>

【问题讨论】:

  • 您的意思是“至少 2 个 &lt;td&gt;”还是“正好 2 个 &lt;td&gt;”?
  • 为什么不使用一些更快的东西,比如表中的类来确定您可能需要什么? (我假设你当然会生成数据)
  • @Jakub:也许 Eron 无法控制 HTML 的生成方式,也许它来自第三方库(客户端或服务器端)、外部 Web 服务、.. .

标签: jquery html-table selection


【解决方案1】:

您应该使用.filter() 方法将tr 减少到仅那些孩子数为2的人

$('table tr').filter(function(){
    return $(this).children().length === 2;
});

演示地址 http://jsfiddle.net/gaby/xTNcG/

【讨论】:

    【解决方案2】:

    至少两个

    $('tr > td:nth-child(2)').parent();
    
    • 如果有td:nth-child(2),那么显然至少有两个tds

    正好两个

    $('tr > td:nth-child(2):last-child').parent();
    
    • 如果有tr &gt; td:nth-child(2):last-child,那么第二个td也是最后一个td,所以肯定只有两个。

    或者像这样:

    $('tr').has('td:nth-child(2)');  // at least two
    
    $('tr').has('td:nth-child(2):last-child');  // exactly two
    

    【讨论】:

    • 我很高兴您不是 10K 用户 - 如果您是,您将能够看到我的愚蠢答案 - 让我们说 eq 没有​​做我认为它做的事情:- / 幸好我很快就删除了
    • @AdamRackis:是的,我有很多这样的。
    【解决方案3】:

    使用长度命令。我想出了这个,你可能需要做一些细微的修改。

    $("table").find("tr").each(function() {
        len = $(this).find("td").length;
        if(len == 2) {
            //do stuff
        }
    });
    

    http://api.jquery.com/length/

    【讨论】:

    • 我想你的意思是$(this).find("td").length
    • 我做到了。感谢您的提醒:)
    猜你喜欢
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    • 2018-04-27
    相关资源
    最近更新 更多