如何仅基于标题行应用一些jquery内容
我有这样的表:
id name number result stuff stuff stuff stuff
我想将class = "red"
仅添加到标题为result
td
所以只有在页面加载时动态地使用jquery的结果列。
您可以使用.index()
获取标头的索引,然后使用:nth-child
选择器应用该类。
的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')
我认为使用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/
我这样做的方法是使用条件和jQuery:
$("th").each(function() { if ($(this).text() === "result") { $(this).addClass('red') } }