2010-10-19 90 views
3

我在其中一本jQuery书籍中看到,您可以突出显示正在排序的列。突出显示一列

$('th.sortable').click(function() { 
    var $th = $(this); 
    var column = $th.index(); 
    var $table = $th.closest('table'); 
    var rows = $table.find('tr:not(:has(th))').get(); 

问:如何将'hightlight'类添加到单击的列中的每个单元格?

回答

5

有一个nth-child选择器,你可以在这种情况下使用。

$('th.sortable').click(function() { 
    var $th = $(this), 
     column = $th.index(), 
     $table = $th.closest('table'); 

    $table.find('tr td:nth-child(' + (column+1) + ')').addClass('highlight'); 
}); 
+0

请注意,_index_是基于零的,而_nth-child_是基于1的。 – 2010-10-19 20:28:19

+0

你说得对,我已经更新了。 – Harmen 2010-10-19 20:28:48

3

我想你可以做这样的事情:

例子:http://jsfiddle.net/4Sg8E/

$('th.sortable').click(function() { 
    var $th = $(this); 
    $th.closest('table').find('td:nth-child(' + ($th.index() + 1) + ')') 
     .css('background','yellow'); 
}); 

它会得到所有<td>元素都是相同的位置,被点击的<th>,并点亮它们。

+0

你的意思是'column + 1'我想,你刚才告诉我'.index()'是基于零的,而'nnth-child'是基于1的。 index = 0 - >第n个孩子(1) – Harmen 2010-10-19 20:31:13

+0

@哈曼 - 别人告诉你,索引是基于零的,是的,我倒过来了。已更新。 – user113716 2010-10-19 20:32:19