替换行颜色,除了'no-alternate-color'类

leo*_*nel 2 javascript jquery html-table

我在JavaScript文件中有这个表达式...

$('tbody tr:even').addClass("alt-row"); 
Run Code Online (Sandbox Code Playgroud)

它交替显示我所有表行的颜色,这没关系.但是我想在tr中添加一个异常类,例如"no-alternate-color".

<table id="invoice">
  <tbody>
  <tr class="headings">
    <th class="item first" style="padding-left:5px;">Unidad</th>
    <th class="description">Descripcion</th>
    <th class="price">Precio</th>
    <th class="quantity">Cantidad</th>
    <th class="linetotal last" style="padding-right:7px;">Total</th>
  </tr>
  <tr class="lineitem alt-row" style="border-bottom:1px solid #e5e5e5;">
    <td class="item_name_data" style="padding:2px 2px 2px 5px;">MacBook Pro 13"</td>
    <td class="description">13-inch: 2.4 GHz
2.4GHz dual-core
Intel Core i5
    </td>
    <td class="price_data">1199.99</td>
    <td class="quantity_data">2</td>
    <td class="linetotal_data" style="padding-right:5px;">2399.98</td>
  </tr>
  <tr class="lineitem" style="border-bottom:1px solid #e5e5e5;">
    <td class="item_name_data" style="padding:2px 2px 2px 5px;">Muji Table</td>
    <td class="description">awesome light brown table</td>
    <td class="price_data">89.99</td>
    <td class="quantity_data">1</td>
    <td class="linetotal_data" style="padding-right:5px;">89.99</td>
  </tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

例如,上面的表最初没有tr中的"alt-row"类,但它是由jQuery函数添加的.

我对jQuery不太熟悉.我怎么能做到这一点?

Jam*_*gne 5

$('tbody tr:not(.no-alternate-color):even').addClass("alt-row");
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/CKeew/

  • 我无法在快速搜索中找到引用,但我记得在IE中遇到了重要的性能问题:不是选择器; 如果这是一个问题你可以尝试使用.not函数:$('tbody tr').not('.no-alternate-color').filter(':even').addClass('alt-row' ) (4认同)

cap*_*rad 5

如果你愿意的话,你可以单独使用CSS(取决于你想要完成的任务)......这样做的东西......

http://jsfiddle.net/xENWM/1/

  • @milkywayjoe如果您没有注意到,两种方法的结果会略有不同.jquery方式将`no-alt`行完全排除在计算奇数和什么是偶数之外,css只是跳过了类中的evens.小提琴看到差异http://jsfiddle.net/xENWM/3/确定它对你来说是否重要. (2认同)