我正在创建一个网站,我希望根据选中的复选框组合来显示不同的 div。我需要知道如何在 switch 语句中引用复选框的类。这是我到目前为止所拥有的。关于如何让它发挥作用有什么建议吗?
我尝试使用“class”来指代复选框的类。例如,如果我单击 checkbox3,并且 checkbox1 已被单击,我希望 div2 出现。如果未单击 checkbox1,我希望出现 div4。
$ (".checkbox3").click(function(){
switch ($('input:checkbox:checked').attr('class')) {
case ".checkbox1" && ".checkbox2":
$(".div1").fadeIn("slow");
break;
case ".checkbox1":
$(".div2").fadeIn("slow");
break;
case ".checkbox2":
$(".div3").fadeIn("slow");
break;
default:
$(".div4").fadeIn("slow");
break;
}
});
这是它引用的 HTML 代码。
<form>
<input type="checkbox" id="redcheck" class="checkbox1">
<input type="checkbox" id="greencheck" class="checkbox2">
<input type="checkbox" id="bluecheck" class="checkbox3">
</form>
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
<div class="div4"></div>
任何帮助都会非常有帮助!谢谢!
最佳答案
您可以引用 jquery 中选中的复选框,如下所示:
$('input:checkbox:checked')
你可以做的是这样的:
$ (".checkbox3").change(function(){
var val='';
if($(this).is(':checked')) {
$.each($('input:checkbox:checked:not(.checkbox3:checkbox)'), function(index) {
val += '.' + $(this).attr('class');
});
switch (val) {
case '.checkbox1.checkbox2':
$(".div1").fadeIn(400);
console.log('case 1');
break;
case '.checkbox1':
$(".div2").fadeIn(400);
console.log('case 2');
break;
case '.checkbox2':
$(".div3").fadeIn(400);
console.log('case 3');
break;
default:
$(".div4").fadeIn(400);
console.log('case 4');
break;
}
} else {
$('div[class*="div"]').hide();
}
});
这里是link to fiddle .
关于javascript - 在 switch 语句中使用复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26183111/