我的桌子有以下html
<table class="tb" id="tb1">
<tr>
<th scope="col">OrderID</th>
<th scope="col">ProductName</th>
<th scope="col">Quantity</th>
</tr>
<tr>....</tr>
当我只点击OrderID,ProductName或Quantity即标题时,我想将css类应用于整个列。
答案 0 :(得分:1)
绑定到click
元素上的th
事件,找到点击的th
索引,并将类添加到相应的col
元素。
工作演示:http://jsbin.com/iraco(可通过http://jsbin.com/iraco/edit进行编辑)
相关代码:
<table id="eggs">
<col /> <col /> <col />
<tr> <th>foo</th> <th>bar</th> <th>baz</th> </tr>
<tr> <td>foo1</td> <td>bar1</td> <td>baz1</td> </tr>
<tr> <td>foo2</td> <td>bar2</td> <td>baz2</td> </tr>
<tr> <td>foo3</td> <td>bar3</td> <td>baz3</td> </tr>
</table>
<script>
$('#eggs th').click(function(){
var index = $(this).prevAll().length;
$('#eggs col')
.removeClass('clicked')
.eq(index).addClass('clicked');
});
</script>
答案 1 :(得分:0)
$(document).ready(function(){
$("table#tb1 th").click(function(){
//from question#788225
var col = $(this).parent().children().index($(this)) + 1;
var t = $("table#tbl");
$("td",t).removeClass("selCol");
$("table#tbl tr td:nth-child("+ col +")").addClass("selCol");
});
});