2017-10-05 30 views
0

我有一些複選框,當你點擊禁用所有其他複選框,直到你不勾選複選框。這很好。但我也想在標籤上加入一個toggleClass'active'。toggleClass標籤上,禁用,直到未點擊

所以當你點擊一個標籤時,它會添加活動類。但是,如果您單擊另一個標籤,則不會添加課程活動,直到您將該課程從以前點擊的標籤上取消切換爲止。對不起,如果這聽起來有點混亂。

我對複選框部分在這裏工作的JS:

$('.test').change(function(){ 
if($('input.test').filter(':checked').length == 1) 
    $('input.test:not(:checked)').attr('disabled', 'disabled'); 
else 
    $('input.test').removeAttr('disabled'); 
}); 

和我有toggleClass爲標籤

$('.holder label').click(function() { 
    $('.holder label').not(this).removeClass('active') 
    $(this).toggleClass('active') 
}) 

但它們在某種程度上需要共同努力。通過查看這個小提琴,你會得到一個更好的主意http://jsfiddle.net/CHQsR/327/

例如,如果您點擊了「Label1」,則其正確(文本變爲粗體並勾選複選框)。但是,如果你點擊「Label2的」應增加「活躍」類(去粗),直至取消選中「Label1的」

感謝

回答

1

看看固定的版本:http://jsfiddle.net/maestrow/uqy77q98/3/

HTML:

<div class="holder"> 
    <label for="checkone">Label1</label> 
    <input type="checkbox" class="test" id="checkone" /> 
</div> 

<div class="holder"> 
    <label for="checktwo">Label2</label> 
    <input type="checkbox" class="test" id="checktwo" /> 
</div> 

<div class="holder"> 
    <label for="checkthree">Label3</label> 
    <input type="checkbox" class="test" id="checkthree" /> 
</div> 

的Javascript:

$('.test').change(function(){ 
    if($('input.test').filter(':checked').length == 1) 
    $('input.test:not(:checked)').attr('disabled', 'disabled'); 
    else 
    $('input.test').removeAttr('disabled'); 

    var id = $(this).attr('id'); 
    $('label[for='+id+']').toggleClass('active'); 
}); 

的CSS:

.active{font-weight:bold;} 

其實你不用在點擊標籤,因爲他們通過for atrribute與相應的複選框連接。在複選框更改時,除禁用/啓用休息複選框外,您應該在相應的標籤上切換類。

此外,你不應該在id標籤中包含散列符號。在選擇器中使用散列時,如果要按ID選擇,即:<div id="mydiv">和用於選擇此div的選擇器是#mydiv,您可以將其用作$('#mydiv')

+0

完美。謝謝 – alexgomy