2012-12-19 93 views
4

所以我有一個問題。我試圖切換複選框以一些CSS添加到父<tr>Jquery Toggle複選框

這是我迄今爲止

$('input[type=checkbox]').toggle(function(){ 

    $(this).parents('tr').addClass('selectCheckBox', 970); 
}, 
function(){ 

    $(this).parents('tr').removeClass('selectCheckBox', 970); 
}); 

然而,這樣做的結果是<tr>沒有receieve的selectCheckBox但該複選框不會被檢查。所以我嘗試了以下幾點:

$('input[type=checkbox]').toggle(function(){ 
    $(this).attr('checked',true); 
    $(this).parents('tr').addClass('selectCheckBox', 970); 
}, 
function(){ 
    $(this).attr('checked',false); 
    $(this).parents('tr').removeClass('selectCheckBox', 970); 
}); 

再次,沒有運氣。

我相信它與複選框ID的外觀有關。

<input type="checkbox" name="select[]" id="select[]"> 

然後我嘗試用\\[\\],因爲我已經在過去使用逃脫[],但沒有運氣。

有沒有辦法讓checkbox檢查?

+0

看到這裏 http://stackoverflow.com/questions/4177159/toggle-checkboxes-on-off –

回答

0

我想通了。我需要使用toggleClass和其餘的jQuery UI參數來獲得所需的效果。

$('input[type=checkbox]').click(function(){ 
    $(this).parents('tr').toggleClass('selectCheckBox', 1000, "easeOutSine"); 
}); 

// Here are the parameteres below 
    .toggleClass(className [, switch ] [, duration ] [, easing ] [, complete ]) 
1

試穿change事件。此外,我認爲toggle事件已被棄用,addClass不採取第二個參數(除非你使用jQuery UI)。

$('input[type=checkbox]').change(function() { 
    $(this).parents('tr').toggleClass('selectCheckBox', $(this).is(':checked')); 
}); 
+0

真棒!這工作完美。我想到了變化事件,但並不認爲它會起作用! addClass有第二個參數來緩解類的影響。它會淡化它。 – Dimitri

+0

哦,對,如果你使用jQuery UI,它有更多的參數... – elclanrs

1

有可能會多一點優化這個辦法:

$('input[type=checkbox]').on('click', function() { 
    var $this = $(this); 
    if ($this.is(':checked')) { 
     $this.closest('tr').addClass('selectCheckbox'); 
    } else { 
     $this.closest('tr').removeClass('selectCheckbox'); 
    } 
}); 

JsFiddle