【问题标题】:How can I apply some jquery stuff only based on header row如何仅基于标题行应用一些 jquery 内容
【发布时间】:2013-03-17 02:16:29
【问题描述】:

我有这样的表:

<table> 
<thead>
   <th>id </th><th>name </th><th>number </th><th>result </th> 
</thead>        
<tbody>
<tr>
 <td>stuff</td>
 <td>stuff</td>
 <td>stuff</td>
 <td>stuff</td> 
</tr>
</tbody>
 </table>

我只想将class = "red" 添加到标头为resulttd

所以只有在页面加载时动态显示带有 jquery 的结果列。

【问题讨论】:

  • 我将成为 Stackoverflow 上的那个混蛋,问你为什么要这样做:这个表是静态的,还是从数据源加载的?如果它是从数据源加载的,那么您提到的类确实应该在模板中;如果你不使用模板,你应该使用一个允许你使用模板的系统,比如 angularjs.org。如果它是静态的,那么这里的答案就是正确的。
  • 添加/删除列而不是着色:stackoverflow.com/questions/8142892/…

标签: javascript jquery html-table jquery-selectors


【解决方案1】:

您可以使用.index() 获取标头的索引,然后使用:nth-child selector 应用类。

jsFiddle

var resultHeaderIndex = $('th:contains("result")').index();
$('td:nth-child(' + (resultHeaderIndex + 1) + ')').addClass('red')

如果您还想将类添加到标题中,那么您可以在获取索引之前简单地添加它:

jsFiddle

var resultHeaderIndex = $('th:contains("result")')
    .addClass('red')
    .index();
$('td:nth-child(' + (resultHeaderIndex + 1) + ')').addClass('red')

【讨论】:

  • 这让我想起了!更简单的方法:$('th:contains("result")').addClass('red')
  • 这不会对整个列着色,只会对下部单元格着色。为标题着色
  • @PitaJ 问题指出“我只想将 class= “red” 添加到标头为结果的 td 中”
  • 好吧,我认为他的意思是包含标题
  • +1 表示短代码。 PitaJ 的反对很容易解决 ... = $('th:contains("result")').addClass('red').index();
【解决方案2】:

我认为使用 jQuery .index().eq() 可以很容易地做到这一点:

(function($){
    $.fn.colorColumn = function(headerText, color){
        var index = this.find("th").filter(function(){
            return ($(this).text() == headerText);
        }).css("backgroundColor", color).index();
        this.find("tr").each(function(){
            $(this).children().eq(index).css({backgroundColor: color});
        })
    }
})(jQuery);

$("table").colorColumn("number", "red");

工作演示:http://jsfiddle.net/pitaj/eG5KE/

【讨论】:

  • 我查看了您的网站pitaz,它给了我数据库连接错误:)
【解决方案3】:

我会这样做的方式是使用条件和 jQuery each:

$("th").each(function() {
    if ($(this).text() === "result") { $(this).addClass('red') }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-17
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    • 2011-09-29
    相关资源
    最近更新 更多