我有一个复选框:
<input type="checkbox" name="mycheckbox" id="mycheckbox" value="0" />
<div style="display:none">
This content should appear when the checkbox is checked
</div>
有没有简单的方法来实现这个?
我有一个复选框:
<input type="checkbox" name="mycheckbox" id="mycheckbox" value="0" />
<div style="display:none">
This content should appear when the checkbox is checked
</div>
有没有简单的方法来实现这个?
$('#mycheckbox').change(function() {
$(this).next('div').toggle();
});
虽然如果您给该DIV分配一个ID,它可以更快地被选择,但这样做会更好:
<input type="checkbox" name="mycheckbox" id="mycheckbox" value="0" />
<div id="mycheckboxdiv" style="display:none">
This content should appear when the checkbox is checked
</div>
<script type="text/javascript">
$('#mycheckbox').change(function() {
$('#mycheckboxdiv').toggle();
});
</script>
http://jsfiddle.net/mblase75/pTA3Y/
如果您想显示div而不再隐藏它,请使用.show()
替换.toggle()
。$(document).ready
。如果你使用了,那么它就不会出现这种情况。 - Blazemonger.toggle()
的作用,没错。如果你希望它反映复选框的确切状态(选中=可见,未选中=隐藏),尝试使用:$('#mycheckboxdiv').toggle($(this).is(':checked'));
并确保初始状态匹配。 - Blazemonger添加一个change
事件,并检查复选框是否被选中。如果复选框被选中,则显示该div。否则,隐藏它:
$('#mycheckbox').change(function(){
if(this.checked) {
$(this).next().show();
} else {
$(this).next().hide();
}
});
$("#mycheckbox").change(function(){
$(this).next().toggle(this.checked);
});
#toggle-content{
display:none;
}
#mycheckbox:checked ~ #toggle-content{
display:block;
height:100px;
}
我已经让它正常工作了
$(document).on('ready',function() {
$('#checkbox').on('change',function(){
if(this.checked) {
console.log("checked");
} else {
console.log("unchecked");
}
})
});
$("#mycheckbox").click(function() { $(this).next("div").toggle() })
$("input#mycheckbox").click(function() {
if($(this).is(":checked") {
$("div").slideDown();
}
else {
$("div").slideUp();
}
})
if ($("#mycheckbox").checked) {
$("div").style.display = "block";
}