【问题标题】:jQuery - how to select a tr that contains th's?jQuery - 如何选择包含 th 的 tr?
【发布时间】:2010-10-06 13:00:24
【问题描述】:

标题几乎说明了一切。
给定一个像

这样的表
<table>
  <tr>
    <th>Header 1</td>
    <th>Header 2</td>
  </tr>
  <tr>
    <td>Datum 1</td>
    <td> Datum 2</td>
  </tr>
  <tr>
    <td>Datum 1</td>
    <td> Datum 2</td>
  </tr>
</table>

如何选择包含第 th 个标题而没有其他标题的行?

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:

    表达式:

    $(function() {
      $("tr:has(th):not(:has(td))").hide();
    });
    

    甚至只是:

    $(function() {
      $("tr:not(:has(td))").hide();
    });
    

    完整示例:

    <html>
    <head>
      <title>Layout</title>
    </head>
    <body>
    <table>
      <tr>
        <th>Header 1</td>
        <th>Header 2</td>
      </tr>
      <tr>
        <td>Datum 1</td>
        <td> Datum 2</td>
      </tr>
      <tr>
        <td>Datum 1</td>
        <td> Datum 2</td>
      </tr>
      <tr>
        <th>Header 3</th>
        <th>Datum 2</td>
      </tr>
    </table>
    <script src="http://www.google.com/jsapi"></script>
    <script>
      google.load("jquery", "1.3.1");
      google.setOnLoadCallback(function() {
        $(function() {
          $("tr:has(th):not(:has(td))").hide();
        });
      });
    </script>
    </body>
    </html>
    

    【讨论】:

    • jQuery 真是太棒了。就是这样。
    【解决方案2】:

    如果可能,最好将表头包含在 元素中

    <table>
        <thead>
            <tr>
                <th></th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td></td>
            </tr>
        </tbody>
    </table>
    

    这样,选择表格标题就很简单了:

    $('thead');
    

    或者只选择

    $('thead tr');
    

    您的标记将更具可读性,并且您的表格样式变得更加容易,因为您可以更轻松地定位表格标题或正文中的元素。

    【讨论】:

      【解决方案3】:
      jQuery("tr:has(th)")
      

      将选择包含至少一个th的每个tr

      kthxbye :)

      【讨论】:

        【解决方案4】:

        不知道它是否像 Dojo CSS3 查询,但如果 jQuery 支持,您可以使用 first-child 伪类:

        tr th:first-child

        tr th:nth-child(1)

        见:http://www.456bereastreet.com/archive/200601/css_3_selectors_explained/

        【讨论】:

          【解决方案5】:

          使用:has 选择器:

          $('tr:has(th)').addClass('sample')
          

          但是,如果您的桌子上有混合的 thtd 孩子,则可能无法使用。

          【讨论】:

            猜你喜欢
            • 2015-02-06
            • 1970-01-01
            • 1970-01-01
            • 2019-05-22
            • 2011-07-09
            • 1970-01-01
            • 1970-01-01
            • 2015-05-11
            • 1970-01-01
            相关资源
            最近更新 更多