首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将类分配给第n棵树

将类分配给第n棵树
EN

Stack Overflow用户
提问于 2014-05-16 13:45:38
回答 4查看 78关注 0票数 1

我有几张桌子,有几张桌子。我正在为第一行分配class='alt',为下一行class='alt-2'和第三行class='alt-3'使用jQuery来求解。如果表中有很多行,我想重复这个脚本。你知道jQuery的一些解决方案吗?谢谢

代码语言:javascript
复制
<table id="news">
    <thead>
      <tr>
        <th>Date</th>
        <th>Headline</th>
        <th id="autor">Author</th>
        <th>Topic</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th colspan="4">2011</th>
      </tr>
      <tr>
        <td>Apr 15</td>
        <td>jQuery 1.6 Beta 1 Released</td>
        <td>John Resig</td>
        <td>Releases</td>
      </tr>
      <tr>
        <td>Feb 24</td>
        <td>jQuery Conference 2011: San Francisco Bay Area</td>
        <td>Ralph Whitbeck</td>
        <td>Conferences</td>
      </tr>
      <tr>
        <td>Feb 7</td>
        <td>New Releases, Videos &amp; a Sneak Peek at the jQuery UI Grid</td>
        <td>Addy Osmani</td>
        <td>Plugins</td>
      </tr>
</table>
EN

回答 4

Stack Overflow用户

发布于 2014-05-16 13:50:26

如果您想以所有的tr为目标,包括thead中的那个,则使用:nth-child

代码语言:javascript
复制
$('#news tr').addClass(function (idx) {
    var rem = idx % 3;
    return 'alt' + (rem == 0 ? '' :'-'+ (rem + 1))
})

演示:Fiddle

票数 2
EN

Stack Overflow用户

发布于 2014-05-16 13:56:25

DEMO

代码语言:javascript
复制
var i = 1;
$("#news tbody tr").each(function () {
    $(this).addClass('alt-' + i);
    i++;
});
票数 0
EN

Stack Overflow用户

发布于 2014-05-16 14:03:44

如果您想包含所有tr

代码语言:javascript
复制
$('#news tr').each(function(i, z){
  $(this).addClass('alt' + (i == 0 ? '' : '-' + (i + 1)));
});

Working Example

或者如果只想在tbody中包含tr

代码语言:javascript
复制
$('#news tbody tr').each(function(i, z){
      $(this).addClass('alt' + (i == 0 ? '' : '-' + (i + 1)));
});

Working Example

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23693374

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档