【问题标题】:jQuery hide div when checkbox checked, show on unchecked选中复选框时jQuery隐藏div,未选中时显示
【发布时间】:2013-01-23 08:19:07
【问题描述】:

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

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

jQuery:

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

我很难让它发挥作用。

【问题讨论】:

标签: javascript jquery html checkbox


【解决方案1】:

确保使用ready 事件。

代码:

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

    });
});

【讨论】:

  • 我相信这一定是问题所在,因为代码在 jsFiddle 上运行良好:jsfiddle.net/mxRCz
  • 我找到了问题所在。
  • 使用标签的正确方法是: 所以复选框必须在标签标签之外
  • 太棒了!非常感谢!
  • 注意:确保您点击了复选框输入 id/class
【解决方案2】:

HTML

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

css

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

javascript/jquery

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多