Javascript jQuery 在复选框选中时隐藏 div,未选中时显示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14757792/
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 17:48:42  来源:igfitidea点击:

jQuery hide div when checkbox checked, show on unchecked

javascriptjqueryhtmlcheckbox

提问by user2035638

I am trying to hide div when user clicks on checkbox, and show it when user unchecks that checkbox. HTML:

我试图在用户单击复选框时隐藏 div,并在用户取消选中该复选框时显示它。HTML:

<div id="autoUpdate" class="autoUpdate">
   content
</div>

jQuery:

jQuery:

<script>
$('#checkbox1').change(function(){
        if (this.checked) {
            $('#autoUpdate').fadeIn('slow');
        }
        else {
            $('#autoUpdate').fadeOut('slow');
        }                   
    });
</script>

I am having a hard time to get this working.

我很难让这个工作。

回答by gdoron is supporting Monica

Make sure to use the readyevent.

确保使用该ready事件。

Code:

代码:

$(document).ready(function(){
    $('#checkbox1').change(function(){
        if(this.checked)
            $('#autoUpdate').fadeIn('slow');
        else
            $('#autoUpdate').fadeOut('slow');

    });
});

回答by overflow

HTML

HTML

<input type="checkbox" id="cbxShowHide"/><label for="cbxShowHide">Show/Hide</label>
<div id="block">Some text here</div>

css

css

#block{display:none;background:#eef;padding:10px;text-align:center;}

javascript / jquery

javascript / jquery

$('#cbxShowHide').click(function(){
this.checked?$('#block').show(1000):$('#block').hide(1000); //time for show
});