我的代码中有红色、绿色和蓝色框作为 3 个不同的 div,我想显示这些 div,具体取决于选中的复选框。
目的是:如果选中蓝色复选框,它应该显示蓝色 div。如果选中绿色 div,则应显示绿色 div。但是,要显示红色 div,应该选中红色和绿色复选框。
这些在我的代码中工作,但有一个问题。如果选中红色和绿色复选框,则会出现红色 div,但也会出现绿色 div。
我需要您帮助的是:如果选中了红色和绿色复选框,则应显示红色 div,但不应显示绿色复选框。 (如果只选中绿色复选框,则应显示绿色 div。)
感谢您的帮助!
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Show Hide Using Checkboxes</title>
<style type="text/css">
.box{
padding: 20px;
display: none;
margin-top: 20px;
border: 1px solid #000;
}
.red{ background: #ff0000; }
.green{ background: #00ff00; }
.blue{ background: #0000ff; }
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if($('#red').is(':checked') && $('#green').is(':checked'))
{
$(".red").show();}
else{ $(".red").hide();
}
if($('#green').is(':checked'))
{
$(".green").show();}
else{ $(".green").hide();
}
if($('#blue').is(':checked'))
{
$(".blue").show();}
else{ $(".blue").hide();
}
});
});
</script>
</head>
<body>
<div>
<label><input type="checkbox" id="red" name="colorCheckbox" value="red"> red</label>
<label><input type="checkbox" id="green" name="colorCheckbox" value="green"> green</label>
<label><input type="checkbox" id="blue" name="colorCheckbox" value="blue"> blue</label>
</div>
<div class="red box">You have selected <strong>red and green checkbox</strong> so i am here</div>
<div class="green box">You have selected <strong>green checkbox</strong> so i am here</div>
<div class="blue box">You have selected <strong>blue checkbox</strong> so i am here</div>
</body>
</html>
最佳答案
$('input[type="checkbox"]').click(function () {
$('.box').hide();
if ($('#blue').is(':checked')) $('.blue.box').show();
if ($('#green').is(':checked') && !$('#red').is(':checked')) $('.green.box').show();
if ($('#red').is(':checked') && $('#green').is(':checked')) $('.red.box').show();
});
关于javascript - 如果选中了 2 个特定的复选框,则显示一个 div,如果选中了 1 个复选框,则显示另一个(如果选中了 2 个复选框,则不显示它),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24914588/