我想使用 jQuery 通过 id 更改列的背景颜色。
html 表格:
<table id="financial_table" style="background-color:#EEE;">
<tbody>
<tr>
<th>Date</th>
<th id="1041051600000">12 2002</th>
<th id="1072587600000">12 2003</th>
<th id="1104210000000">12 2004</th>
<th id="1135746000000">12 2005</th>
<th id="1167282000000">12 2006</th>
<th id="1198818000000">12 2007</th>
<th id="1230440400000">12 2008</th>
<th id="1261976400000">12 2009</th>
<th id="1293512400000">12 2010</th>
<th id="1325048400000">12 2011</th>
</tr>
<tr>
<td>Share</td>
<td>12.1</td>
<td>14.08</td>
<td>15.97</td>
<td>16.98</td>
<td>18.14</td>
<td>21.2</td>
<td>22.67</td>
<td>22.43</td>
<td>22.38</td>
<td>23.77</td>
</tr>
<tr>
<td>Revenue</td>
<td>12.1</td>
<td>14.08</td>
<td>15.97</td>
<td>16.98</td>
<td>18.14</td>
<td>21.2</td>
<td>22.67</td>
<td>22.43</td>
<td>22.38</td>
<td>23.77</td>
</tr>
</tbody>
</table>
jQuery:
$(function() {
$('#1135746000000').css('background-color','blue');
});
我知道它只能更改id为1135746000000的第一个背景。我想用这个id更改整个列的背景颜色。
最佳答案
合并.index()
和 :nth-child()
选择器
Search for a given element from among the matched elements.
If no argument is passed to the
.index()
method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.
Selects all elements that are the nth-child of their parent.
Because jQuery's implementation of
:nth-
selectors is strictly derived from the CSS specification, the value ofn
is "1-indexed", meaning that the counting starts at 1.
可能的解决方案如下所示:
// get the index of the column
var colIdx = $("#1041051600000").index();
// grab all <td> and <th> elements from the (colIdx + 1) column
$("td, th").filter(":nth-child(" + (colIdx + 1) + ")")
.css("background-color", "red");
var colIdx = $("#1041051600000").index();
$("td, th").filter(":nth-child(" + (colIdx + 1) + ")")
.css("background-color", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th>Date</th>
<th id="1041051600000">12 2002</th>
<th id="1072587600000">12 2003</th>
<th id="1104210000000">12 2004</th>
</tr>
<tr>
<td>Share</td>
<td>12.1</td>
<td>14.08</td>
<td>15.97</td>
</tr>
<tr>
<td>Revenue</td>
<td>12.1</td>
<td>14.08</td>
<td>15.97</td>
</tr>
</tbody>
</table>
关于jquery - 如何通过id更改html表格中列的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13420258/