【问题标题】:jQuery how to select column in table based on table headingjQuery如何根据表格标题选择表格中的列
【发布时间】:2018-10-04 05:31:11
【问题描述】:

我试图弄清楚如何根据表格标题选择表格中的列。到目前为止,我通过大量谷歌搜索发现的是:

<html>
<body>
   <table>
      <tr><th class='x29'>A</th><th class='x29'>B</th><th class='x29'>C</th><th class='x29'>D</th></tr>
      <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
      <tr><td>5</td><td>6</td><td>7</td><td>8</td></tr>
      <tr><td>9</td><td>10</td><td>11</td><td>12</td></tr>
   </table>
   <script>
       $(document).ready(function() {
          var l_col;
          $('th.x29').each(function () {
             if ($(this).text() == 'C') {
                l_col = $(this).index();
                $(this).closest('tr').next().children().eq(l_col+1).append("<b>A String</b>");
             }
          });
       });
   </script>
</body>
</html>

不幸的是,这只会将“A String”附加到标题为“C”的列的第一行。如何将“A String”附加到标题为“C”的整个列。比我更好的代码将不胜感激。

【问题讨论】:

  • 那么最接近的可能不是正确的选择。
  • 你会推荐什么?
  • 您是否尝试过使用查找或其他过滤器
  • 恐怕这是我使用 jQuery 的第一天
  • 那么你开始使用 jquery 选择器阅读是件好事

标签: jquery html-table


【解决方案1】:

您可以使用containsindexnth:child 选择器的组合来获取每行的第n 个单元格。

代码:

  $(document).ready(function () {
      $("tr td:nth-child(" + ($('th.x29:contains("C")').index()+1) + ")").append("<b>A String</b>")
  });

演示:http://jsfiddle.net/IrvinDominin/VWr7X/

【讨论】:

    【解决方案2】:

    怎么样

    $(document).ready(function () {
        var l_col  = $('th.x29').filter(function(){
            return $(this).text() === 'C';
        }).index() +1 ;
    
        $('tr td:nth-child(' + l_col + ')').append('<b>A String</b>');
    
    });
    

    演示地址 http://jsfiddle.net/HfjLa/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-12
      • 1970-01-01
      相关资源
      最近更新 更多