【问题标题】:Using jQuery to add class to first TD on each table row使用 jQuery 将类添加到每个表行的第一个 TD
【发布时间】:2011-04-24 22:35:04
【问题描述】:

我有一张我正在使用的桌子,就像这样:

<table width="100%" border="0" cellspacing="0" cellpadding="0" id="tablecontent">
  <tr class="tablerow">
    <td>This is the td I want to add a class to.</td>
    <td class="cell2">Stuff</td>
    <td class="cell3">Stuff</td>
  </tr>
  <tr class="tablerow">
    <td>This is the td I want to add a class to.</td>
    <td class="cell2">Stuff</td>
    <td class="cell3">Stuff</td>
  </tr>
</table>

每行中的第一个 TD 标记没有可使用的类或 ID。我无权更改 HTML 输出,所以我想添加一些 jQuery 来定位每个 tablerow 的第一个 TD 标记。我该怎么做?

【问题讨论】:

    标签: jquery html css class html-table


    【解决方案1】:
    $('#tablecontent td:first-child').addClass('someClass');
    

    这使用the first-child selector 来选择#tablecontent 表中的所有&lt;td&gt; 元素,它们是其父级的first-child

    示例: http://jsfiddle.net/duKKC/

    【讨论】:

      【解决方案2】:

      你可以试试下面的jQuery

      $('.tablerow').each(function(index) {
          $(this).children('td').first().addClass('class');
      });
      

      这会解决你的问题:)

      【讨论】:

        【解决方案3】:
        $(".tablerow").find("td:first-child").addClass('class');
        

        【讨论】:

          【解决方案4】:

          我相信以下方法会起作用:

          $('.tablerow td:first-child').addClass('class');
          

          【讨论】:

            【解决方案5】:
            $('#tablecontent td:first-child').addClass("first-row");
            

            【讨论】:

              猜你喜欢
              • 2021-07-28
              • 2010-10-31
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2023-03-24
              • 1970-01-01
              • 2016-11-08
              • 2021-05-04
              相关资源
              最近更新 更多