2011-11-30 29 views
0

當需要選中或取消選中該行中的複選框時,需要更改整行的樣式。基於複選框更改樣式w/jQuery

function myFunc() { 
    if ($(".chkbx:checked").length) { 
     $(this).parent().parent().css("background-color","red"); 
    } else { 
     $(this).parent().parent().css("background-color","green"); 
    } 
} 

myFunc(); 

$(".chkbx").change(myFunc); 
<table> 
    <tr> 
     <td><input type="checkbox" class="chkbx" checked></td> 
     <td>label 1</td> 
    </tr> 
    <tr> 
     <td><input type="checkbox" class="chkbx" checked></td> 
     <td>label 1</td> 
    </tr> 
    <tr> 
     <td><input type="checkbox" class="chkbx" checked></td> 
     <td>label 1</td> 
    </tr> 
</table> 

我覺得我失去了一些東西......

回答

3
$('.chkbx').change(function(){ 
    var $this = $(this), 
     color = ($this.is(':checked')) ? 'red' : 'green'; 
    $this.closest('tr').css('background-color', color); 
}); 

演示:http://jsfiddle.net/6dR8C/1/

+0

沒有什麼不對,但通常您會在使用jQuery框架時看到以$爲起點的jQuery對象開始的變量。 '$ color'使得它看起來好像該變量正在尊重jQuery,在我看來,'color'將是一個更好的選擇,因爲它只是一個字符串。 – Justin808

0

你可以這樣做:

$(document).ready(function() { 
    $(".chkbx").click(function() { 
     if ($(this).is(":checked")) { 
      $(this).closest("tr").css('background-color' ,'red'); 
     } 
     else { 
      $(this).closest("tr").css('background-color' ,'green'); 
     } 
    }); 
}); 
+0

你的意思是'父母( 「TR」)'。 – Purag

+0

某些複選框可以在頁面加載時進行檢查,並且我需要在頁面加載時應用樣式,然後單擊任何複選框。 – santa

+0

@Purmou'closest'會正常工作。 – AlienWebguy

1

看到一個例子here

問題是您的if正在檢查所有匹配.chkbx:checked的元素。如果選中任何複選框,則爲真。你必須檢查一個複選框,this

更新:樣式初始化爲here

+0

你說得對。我也需要在頁面加載時分配樣式,而不僅僅是點擊。 +1 for jsfiddle – santa

+1

虛構-1強制大家去另一個網站查看您的解決方案。如果JSFiddle永遠消失,這個答案變得毫無用處。 – Maverick

+0

@santa我更新了jsFiddle。 – Justin808

0

這裏是一個有效的解決方案:http://jsfiddle.net/gDtLX/

基本上,你的if說法有點過,彷彿複選框中的任何被檢查的話將永遠是正確的。然後,在加載時,您可以使用jQuery的trigger()在每個複選框上觸發change事件,而不是使用myFunc()手動調用該函數。

0

我會用一個CSS類然後添加/刪除類上的複選框是否被選中或不

$(function(){ 
    $("input.chkbx").click(function(){ 
    if($(this).is("checked")) { 
     $(this).parent("tr").addClass('checkedRow'); 
    } else { 
     $(this).parent("tr").removeClass('checkedRow'); 
    } 
    }); 
}); 

通過使用類的顏色(或其它樣式)可以很容易地通過樣式表修改。

+0

是的,我將改爲上課。我需要確保樣式適用於加載,而不僅僅是點擊。謝謝。 – santa

+0

在您的示例腳本中,您在頁面加載時調用myFunc(),它將爲您執行此操作。 :) –

+0

是的,這是主意......但有些不對。謝謝。 – santa

0

據我所知,你想遍歷你的複選框,如果複選框是紅色的,則表格行變紅,否則爲綠色。此外,每當任何複選框發生更改時,您都希望這樣做。

你應該使用jQuery的「each」方法遍歷複選框。就像這樣:

function myFunc() { 
    $('.chkbx').each(function() { 
     var $this = $(this); 
     if ($this.is(':checked')) { 
      $this.parents('tr').css("background-color","red"); 
     } else { 
      $this.parents('tr').css("background-color","green"); 
     } 
    }); 
} 

myFunc(); 

$(".chkbx").change(myFunc); 

你可以看到例如工作在這裏的源代碼: http://jsbin.com/awexak/edit#preview