我遇到了一个挑战,要根据th类更改td元素的背景色。下面是html代码,它的th类称为bots,我必须更改bots类下面所有td元素的背景色。
<table border="1" class="CSSTableGenerator" id="myTable">
<tr>
<th>Component</th>
<th>Properties</th>
<th class="bots">J10</th>
<th>J11</th>
<th>J12</th>
<th>J13</th>
</tr>
<tr>
<td>GenerateAlternateTagUrlDroplet</td>
<td>alternateTagConfiguration</td>
<td class="trueValue">/com//jec/website/seo/</td>
<td class="trueValue">/com//jec/website/seo/</td>
<td class="trueValue">/com//jec/website/seo/</td>
<td class="trueValue">/com//jec/website/seo/</td>
</tr>
<tr>
<td>AlternateTagUrlDroplet</td>
<td>tagConfiguration</td>
<td class="trueValue">/jec/website/seo/</td>
<td class="trueValue">/jec/website/seo/</td>
<td class="trueValue">/jec/website/seo/</td>
<td class="trueValue">/jec/website/seo/</td>
</tr>
</table>
有人能帮助我使用jquery代码来实现这一点吗?
事先非常感谢。
发布于 2016-06-12 16:34:10
您可以使用map()返回带有.bots类的索引数组,然后用相同的索引更改td的css。
var bots = $('tr th.bots').map(function() {
return $(this).index();
}).get()
$('tr:not(:first) td').each(function() {
if (bots.indexOf($(this).index()) != -1) $(this).css('background', 'blue')
})<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" class="CSSTableGenerator" id="myTable">
<tr>
<th>Component</th>
<th>Properties</th>
<th class="bots">J10</th>
<th>J11</th>
<th class="bots">J12</th>
<th>J13</th>
</tr>
<tr>
<td>GenerateAlternateTagUrlDroplet</td>
<td>alternateTagConfiguration</td>
<td class="trueValue">/com//jec/website/seo/</td>
<td class="trueValue">/com//jec/website/seo/</td>
<td class="trueValue">/com//jec/website/seo/</td>
<td class="trueValue">/com//jec/website/seo/</td>
</tr>
<tr>
<td>AlternateTagUrlDroplet</td>
<td>tagConfiguration</td>
<td class="trueValue">/jec/website/seo/</td>
<td class="trueValue">/jec/website/seo/</td>
<td class="trueValue">/jec/website/seo/</td>
<td class="trueValue">/jec/website/seo/</td>
</tr>
</table>
发布于 2016-06-12 16:40:25
一种选择是按照以下方针做一些事情:
科德芬
var nthChild = $('.bots').index() + 1; // Add 1 since index starts at 0
$("td:nth-child(" + nthChild + ")").css("background", 'yellow');发布于 2016-06-12 16:49:35
也许可以得到所有的th.bots索引,并使用该颜色的tds。假设您有jQuery:
$('th.bots').each(function(){
$('td:nth-child('+($(this).index() + 1)+')').css('background-color', 'blue');
});编辑:不包括同一页上的其他表http://codepen.io/anon/pen/PzNZrE
$('th.bots').each(function(){
$(this).parents('table').children().find('td:nth-child('+($(this).index() + 1)+')').css('background-color', 'blue');
});https://stackoverflow.com/questions/37776578
复制相似问题