0

複数のTBODY要素(1年の各月に1つ)を含むテーブルがあり、TBODY要素内で行の色を変更したいと考えています。

説明のために、次の基本構造のテーブルがあります。

<table>
  <tbody>
    <tr>
      <th>October</th>
      <th>Total</th>
    </tr>
    <tr>
      <td>Item 1</td>
      <td>500</td>
    </tr>
    <tr>
      <td>Item 2</td>
      <td>1000</td>
    </tr>
    <tr>
      <td>Item 3</td>
      <td>1400</td>
    </tr>
  </tbody>
  <tbody>
    <tr>
      <th>November</th>
      <th>Total</th>
    </tr>
    <tr>
      <td>Item 1</td>
      <td>800</td>
    </tr>
    <tr>
      <td>Item 2</td>
      <td>400</td>
    </tr>
    <tr>
      <td>Item 3</td>
      <td>200</td>
    </tr>
  </tbody>
  ... a <tbody> for all 12 months ...
</table>

そして、次のJQuery呼び出し:

<script type="text/javascript">
    $(function () {
        $("table > tbody > tr:even").addClass("alternate-row");
    });
</script>

しかし、JQueryはテーブル全体を1つの論理グループとして扱い、 TBODYの場所に関係なく、すべての奇数行に代替行クラスを適用します。

言い換えれば、私が欲しいのは:

October (normal color)
  Item #1 (normal color)
  Item #2 (alt color)
  Item #3 (normal color)
November (normal color)
  Item #1 (normal color)
  Item #2 (alt color)
  Item #3 (normal color)
... etc

代わりに、上記のJQueryで得られるものは次のとおりです。

October (alt color)
  Item #1 (normal color)
  Item #2 (alt color)
  Item #3 (normal color)
November (alt color)
  Item #1 (normal color)
  Item #2 (alt color)
  Item #3 (normal color)
... etc

つまり、何らかの理由でTBODYセレクターを認識しません。私は何を間違えましたか?

ありがとう。

4

2 に答える 2

4

私が問題を正しく理解しているなら、これはあなたが望むものかもしれません:

$("table > tbody").each( function() {
    $("tr:even:not(:first)", this).addClass("alternate-row");
} );

jsfiddle

コードの問題は、すべてのTRを一度に選択することです。

于 2013-01-15T23:19:03.350 に答える
1

OPのオリジナルの「私が欲しいもの」を見て

ソリューションはより似ています

$(document).ready(function () {
  $("tbody").find("tr:even:not(:first)").addClass("alternate-row");
});

フィドル

于 2013-01-15T23:44:15.577 に答える