2014-03-19 40 views
-1

我有幾個表格。我試圖通過jQuery添加一個類到表中的所有行,當我按鏈接所有。我怎樣才能做到這一點,而無需在表中添加類和id。現在類添加到每個表中的所有行,當我點擊任何表中的鏈接「全部」。我不知道如何選擇擁有鏈接「全部」的表。jQuery更改表格行的背景顏色

Here's a fiddle我在想什麼。

$(function(){ 
    $('.table tbody input[type=checkbox]').change(function() { 
     $(this).closest('table tbody tr').toggleClass("np-tr-selected", this.checked); 
    }); 
    $(".all").click(function(){ 
     $('table tbody tr').addClass("np-tr-selected"); 
    }); 
}) 
+0

當您單擊全部,你也想的複選框被選中,或只是背景改變顏色? – j08691

+0

這個問題只是關於背景 – user3127896

回答

1

你可以這樣做是這樣的:

$(".all").click(function(){ 
    $('tbody tr', $(this).closest('table')).addClass("np-tr-selected"); 
}); 

小提琴:http://jsfiddle.net/Wy22s/24/

1

您可以使用下面的代碼片段:

DEMO jsFiddle

$(function(){ 
    $('.table tbody input[type=checkbox]').change(function() { 
     $(this).closest('tr').toggleClass("np-tr-selected", this.checked); 
    }); 
    $(".all").click(function(){ 
     $(this).closest('table').find('tbody tr').addClass("np-tr-selected").find(':checkbox').prop('checked', true); 
    }); 
}) 
1

你將添加類表中,不是所有的行,這樣做的方法是從$開始(這)然後根據你的html需要多次上傳到.parent(),直到你點擊表格元素。

<table class="hitme"> 
    <tbody> 
    <tr> 
    <td><input type="checkbox" class="someclass" name="somename"> 

需要像

$('.somename').on('click', function(){ 
    $(this).parent().parent().parent().parent().addClass('someotherclass'); 
    }) 
+0

'$(this).closest('table')'真的更好 –

+0

是的,當時沒來找我:D – alou

1

如果你想改變背景顏色,並檢查複選框單擊所有,使用時:

$(function(){ 
    $('.table tbody input[type=checkbox]').change(function() { 
     $(this).closest('table tbody tr').toggleClass("np-tr-selected", this.checked); 
    }); 
    $(".all").click(function(){ 
     $(this).closest('table').find('tr:gt(0)').addClass("np-tr-selected").find('input').prop('checked', true); 
    }); 
}) 

jsFiddle example

如果您不需要擔心複選框,清除.find('input').prop('checked', true);