Javascript 选中复选框时展开 Div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7996291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:19:04  来源:igfitidea点击:

When Checkbox is Checked Expand Div

javascriptjqueryhtml

提问by Satch3000

I have a checkbox:

我有一个复选框:

<input type="checkbox" name="mycheckbox" id="mycheckbox" value="0" />
<div style="display:none">
This content should appear when the checkbox is checked
</div>

Does anyone have a simple way to do this?

有没有人有一个简单的方法来做到这一点?

回答by Blazemonger

This will show it when the checkbox is checked, and hide it again when the checkbox is unchecked:

这将在选中复选框时显示它,并在取消选中复选框时再次隐藏它:

$('#mycheckbox').change(function() {
    $(this).next('div').toggle();
});

...although it would be better if you'd assign that DIV an id, so it could be selected more quickly:

...虽然如果您为该 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/

http://jsfiddle.net/mblase75/pTA3Y/

If you want to show the div without hiding it again, replace .toggle()with .show().

如果您想显示 div 而不再次隐藏它,请将其替换.toggle().show().

回答by Rob W

Attach a changeevent, and check whether a checkbox is checked or not. If the checkbox is checked, show the div. Otherwise, hide it:

附加一个change事件,并检查复选框是否被选中。如果选中该复选框,则显示 div。否则,隐藏它:

$('#mycheckbox').change(function(){
    if(this.checked) {
        $(this).next().show();
    } else {
        $(this).next().hide();
    }
});

You should also have a look at the jQuery docs, before asking such a trivial question.

在提出这样一个微不足道的问题之前,您还应该查看jQuery 文档

回答by jrummell

$("#mycheckbox").change(function(){ 
    $(this).next().toggle(this.checked); 
});

回答by vijayscode

If you are looking for only css solution, then this can help you.

如果您只是在寻找 css 解决方案,那么这可以帮助您。

#toggle-content{
display:none;
}
#mycheckbox:checked ~ #toggle-content{
  display:block;
  height:100px;

}

Fiddle

小提琴

回答by Manuel van Rijn

$("input#mycheckbox").click(function() {
    if($(this).is(":checked") {
        $("div").slideDown();
    }
    else {
        $("div").slideUp();
    }
})

回答by L3viathan

if ($("#mycheckbox").checked) {
   $("div").style.display = "block";
}

回答by jessegavin

$("#mycheckbox").click(function() { $(this).next("div").toggle() })