2010-10-19 91 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