【问题标题】:Show/Hide div when checkbox selected [closed]选中复选框时显示/隐藏 div [关闭]
【发布时间】:2013-10-18 10:38:25
【问题描述】:

当用户选中复选框时,我需要显示其他内容。我有以下代码:

<!DOCTYPE html>
<html>
<head>
<title>Checkbox</title>
<script type="text/javascript">


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

});
});

</script>
</head>
<body>
Add another director <input type="checkbox" id="checkbox1"/>
<div id="autoUpdate" class="autoUpdate">
content
</div>
</body>
</html>

非常感谢一些帮助,对 HTML5、CSS3 以及非常基本的 JavaScript/jQuery 有很好的了解。

【问题讨论】:

  • 您是否在该页面上包含了 jQuery 库?我在示例代码中看不到 &lt;script type="text/javascript" src='//code.jquery.com/jquery-1.9.1.js'&gt;&lt;/script&gt; 之类的东西。
  • 你的问题到底是什么?
  • 包含库,根本无法工作?选中复选框时内容不会隐藏
  • @user2890036 您希望它在被选中时隐藏?然后你必须做 !this.checked
  • 现已解决,很抱歉造成混淆。由@Anton 轻松解决,不会有那么大的误导性。简单的代码修复,但正如我所说 - 我对 Javascript 知之甚少。

标签: javascript jquery html checkbox show-hide


【解决方案1】:

您的脑海中缺少 jQuery,您必须包含它。

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>

您的代码有效DEMO

根据新信息更新

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

DEMO

你也可以只使用 .fadeToggle()

$(document).ready(function () {
    $('#checkbox1').change(function () {
      $('#autoUpdate').fadeToggle();
    });
});

【讨论】:

  • 感谢您的回答 - 它现在可以正常工作,而不是我希望从一开始就隐藏它,任何想法我将如何解决这个问题。再次感谢。
  • 你可以使用 css,#autoUpdate{display:none}@user2890036 检查这个小提琴jsfiddle.net/Alfie/3WEVr/8
  • 谢谢!一切都按要求工作。
【解决方案2】:

头中包含jquery

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
    $('#checkbox1').change(function(){
    if($(this).is(":checked"))
    $('#autoUpdate').fadeIn('slow');
    else
    $('#autoUpdate').fadeOut('slow');

    });
    });
</script>

见demo

参考:checked和is()

【讨论】:

    【解决方案3】:

    请用下面的代码替换你的代码,它将帮助你

    <!DOCTYPE html>
    <html>
    <head>
    <title>Checkbox</title>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript">
    
    
    $(document).ready(function(){
    $('#checkbox1').change(function(){
    if(this.is(":checked") == true)
    $('#autoUpdate').fadeIn('slow');
    else
    $('#autoUpdate').fadeOut('slow');
    
    });
    });
    
    </script>
    </head>
    <body>
        Add another director <input type="checkbox" id="checkbox1"/>
    <div id="autoUpdate" class="autoUpdate">
    content
    </div>
    </body>
    </html>
    

    【讨论】:

    • 你需要用 jQuery $() 包装它所以 $(this).is(':checked')
    猜你喜欢
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多