我有这个重复的HTML代码。
9 9 9 9 9 8 9 8 7
9 7 7 8 7 6 7 6 6
9 7 4 3 3 3 4 5 6
9 6 2 0 0 0 0 3 6
9 6 2 0 0 0 0 1 6
9 6 2 0 0 0 0 3 6
9 7 4 2 2 2 1 3 6
9 7 7 8 7 6 7 6 6
想要的行为是隐藏/显示div c2内容独立基于input.c1选中与否:
<div id="id1" class="questio">
<input type="checkbox" class="c1">
<div class="c2">Content</div>
</div>
<div id="id2" class="questio">
<input type="checkbox" class="c1">
<div class="c2">Another Content</div>
</div>
<div id="id3" class="questio">
<input type="checkbox" class="c1">
<div class="c2">Another Content</div>
</div>
我试过这样的事,但我不能继续下去:
if ($(".c1").is(":checked")) {
$('.c2').show();
}
答案 0 :(得分:1)
您需要使用this
来引用所点击的元素,否则您将定位太多您不需要的元素。
$('input.c1').click(function() {
$(this).next('div.c2').toggle($(this).is(":checked"))
})
.c2 {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id1" class="questio">
<input type="checkbox" class="c1">
<div class="c2">Content</div>
</div>
<div id="id2" class="questio">
<input type="checkbox" class="c1">
<div class="c2">Another Content</div>
</div>
<div id="id3" class="questio">
<input type="checkbox" class="c1">
<div class="c2">Another Content</div>
</div>
答案 1 :(得分:0)
试试这个:
var div1 = $("id1");
var c2OfDiv1 = div1.find(".c2");
c2OfDiv1.hide(); //or c2OfDiv1.show();
答案 2 :(得分:0)
你非常接近。
//you can find the c1's that are checked
$(".c1:checked").each(function() {
//you can then find their parent questio (with the '.' for the selector)
//then find the related c2 and show it.
$(this).closest('.questio').find('.c2').show();
});
虽然给你的标记你可以用css完全做到这一点。
.questio .c1:not(:checked) + .c2 {
display: none;
}
<div id="id1" class="questio">
<input type="checkbox" class="c1">
<div class="c2">Content</div>
</div>
<div id="id2" class="questio">
<input type="checkbox" class="c1">
<div class="c2">Another Content</div>
</div>
<div id="id3" class="questio">
<input type="checkbox" class="c1">
<div class="c2">Another Content</div>
</div>
答案 3 :(得分:0)
你可以使用parent(),就像这个简写:
$(".c1").on('change', function() {
var parent = $(this).parent().find('.c2');
parent[$(this).is(":checked") ? "show" : "hide"]();
});
&#13;
.c2 {
display:none
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="id1" class="questio">
<input type="checkbox" class="c1">
<div class="c2">Content</div>
</div>
<div id="id2" class="questio">
<input type="checkbox" class="c1">
<div class="c2">Another Content</div>
</div>
<div id="id3" class="questio">
<input type="checkbox" class="c1">
<div class="c2">Another Content</div>
</div>
&#13;