我有多个复选框。当我点击相应的按钮时,我想检查并取消选中其中一些或全部。
例如,当我点击“全部检查”按钮时,我想要检查所有按钮。当我点击“男性”按钮时,我只想检查“类”等于“男性”的复选框。当我点击“女性”按钮时,我只想检查类等于“女性”的复选框。当我点击“无”按钮时,我只想检查类等于“无”的复选框。我怎么能用jquery做到这一点?
<br>
<div>
<input type="checkbox" class="check_all"> Check all
<input type="checkbox" class="check_all_females"> Females
<input type="checkbox" class="check_all_males"> Males
<input type="checkbox" class="check_all_none"> None
</div>
<input type="checkbox" class='male'> John<BR>
<input type="checkbox" class='male'> Maria<BR>
<input type="checkbox" class='male'> Ali<BR>
<input type="checkbox" class='male'> Tural<BR>
<input type="checkbox" class='female'> John<BR>
<input type="checkbox" class='female'> Fuass<BR>
<input type="checkbox" class='female'> Jadsa<BR>
<input type="checkbox" class='none'> Dasda<BR>
<input type="checkbox" class='none'> Wers<BR>
<input type="checkbox" class='none'> Saqa<BR>
答案 0 :(得分:7)
这样做:
$(function(){
$("div.mains input:checkbox").click(function(){
var rel = $(this).attr("rel"),
checked = $(this).is(":checked");
switch(rel)
{
case "all":
if(!checked)
{
$(".sub input:checkbox").removeAttr("checked");
}
else
{
$(".sub input:checkbox").attr("checked", "checked");
}
break;
default:
if(!checked)
{
$(".sub input." + rel).removeAttr( "checked");
}
else
{
$(".sub input." + rel).attr( "checked", "checked");
}
}
});
});
HTML
<br>
<div class="mains">
<input type="checkbox" rel="all" class="check_all"> Check all
<input type="checkbox" rel="female" class="check_all_females"> Females
<input type="checkbox" rel="male" class="check_all_females"> Males
<input type="checkbox" rel="none" class="check_all_females"> None
</div>
<div class="sub">
<input type="checkbox" class='male'> John<BR>
<input type="checkbox" class='male'> Maria<BR>
<input type="checkbox" class='male'> Ali<BR>
<input type="checkbox" class='male'> Tural<BR>
<input type="checkbox" class='female'> John<BR>
<input type="checkbox" class='female'> Fuass<BR>
<input type="checkbox" class='female'> Jadsa<BR>
</div>
试试这个小提琴:http://jsfiddle.net/2R2CC/