2014-01-29 55 views
1

我有一個包含3個不同類別的列表,並且根據是否選中複選框,我需要讓它們隱藏或可見。如何在選中複選框時使類可見

我的HTML

<input type="checkbox" name="option" value="one">One<br> 
<input type="checkbox" name="option" value="two">Two<br> 
<input type="checkbox" name="option" value="three">Three<br> 
<ul> 
    <li class='one'>alpha</li> 
    <li class='two'>beta</li> 
    <li class='three'>gamma</li> 
</ul> 

如何將我得到它,從而選擇一個複選框時,只。一是看得見?如果選擇One和Two,則.one和.two可見。

+0

如果檢查一個和兩個? –

+0

無論選中哪個複選框,我都希望可見。對困惑感到抱歉。 –

回答

2

然後嘗試

//dom ready handler 
jQuery(function() { 
    //element and attribute equals selector to select all input elements with name option and register a change event handelr 
    $('input[name="option"]').change(function() { 
     //find the target element using class selector and the changed checkbox's value and then use toggle() to set visibility according to the checked state of the checkbox 
     $('.' + this.value).toggle(this.checked) 
    }).change(); //trigger the change event on page load to set the proper initial values 
}) 

演示:Fiddle

+0

你必須隱藏之前! –

+0

@LarsEbert不需要,因爲更改事件在頁面加載時手動觸發請參閱小提琴 –

+0

對不起,我有點快。當我評論時,並沒有手動觸發。 –

0

請記住,與複選框,用戶可以選擇多個選項!

$('ul li').hide(); 
$('input').change(function() { 
    if($(this).prop('checked')) { 
     $('.' + $(this).attr('value')).show(); 
    } else { 
     $('.' + $(this).attr('value')).hide(); 
    } 
}); 
0

演示FIDDLE

HTML

<input type="checkbox" class="one" name="option" value="one">One<br> 
<input type="checkbox" class='two' name="option" value="two">Two<br> 
<input type="checkbox" class='three' name="option" value="three">Three<br> 
<ul> 
    <li class='one' style="display:none;">alpha</li> 
    <li class='two' style="display:none;">beta</li> 
    <li class='three' style="display:none;">gamma</li> 
</ul> 

jQuery的

$('input[type="checkbox"]').click(function(){ 
$('li.'+$(this).attr('class')).toggle(); 
}); 
0

jQuery的會是這樣簡單的方法,但是這可以用CSS來完成。

注意:這種方法不靈活,HTML結構中的特定

Codepen Demo

HTML

<input class='one' type="checkbox" name="option1" value="one">One<br> 
<input class='two' type="checkbox" name="option2" value="two">Two<br> 
<input class='three' type="checkbox" name="option3" value="three">Three<br> 
<ul> 
    <li class='one'>alpha</li> 
    <li class='two'>beta</li> 
    <li class='three'>gamma</li> 
</ul> 

CSS

li { 
    display:none; 
} 

input[type=checkbox].one:checked ~ ul li.one, 
input[type=checkbox].two:checked ~ ul li.two, 
input[type=checkbox].three:checked ~ ul li.three { 
display:block; 
} 
0

你可以不喜歡它:http://jsfiddle.net/84sAy/

$('input').each(function(){ 
$(this).change(function(checked){ 
console.log() 
    if ($(this)[0].checked) 
{ 
    $("."+$(this).val()).hide() 
} 
    else 
    { 
     $("."+$(this).val()).show() 
    } 
}) 

})

相關問題