jQuery - 如何选择包含th的tr?

Geo*_*uer 6 jquery jquery-selectors

标题几乎说明了一切.
给出一个像这样的表

<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>
Run Code Online (Sandbox Code Playgroud)

如何选择包含th标题而不包含其他标题的行?

cle*_*tus 25

表达:

$(function() {
  $("tr:has(th):not(:has(td))").hide();
});
Run Code Online (Sandbox Code Playgroud)

甚至只是:

$(function() {
  $("tr:not(:has(td))").hide();
});
Run Code Online (Sandbox Code Playgroud)

完整示例:

<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>
Run Code Online (Sandbox Code Playgroud)

  • jQuery令人惊叹.就这些. (3认同)

Ste*_*atz 7

如果可能,最好将表头封装在<thead>元素中

<table>
    <thead>
        <tr>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td></td>
        </tr>
    </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

这样,选择表头就像下面这样简单:

$('thead');
Run Code Online (Sandbox Code Playgroud)

或者只选择<tr>

$('thead tr');
Run Code Online (Sandbox Code Playgroud)

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