【问题标题】:jQuery show/hide div onclick checkbox multiplejQuery 显示/隐藏 div onclick 复选框多个
【发布时间】:2015-10-10 23:03:03
【问题描述】:

我的小提琴有效,但如果我单击多个复选框,我需要隐藏的 div 保持显示。而且我只需要在再次单击 NO 复选框后隐藏它。例如,我单击第一个复选框,div 显示。我单击第二个,div 保留。我取消选中第二个,div 保留。我取消选中第一个(这意味着没有再次检查)并且 div 隐藏。我尝试使用 slideToggle,但一旦不再选中复选框,它就不会隐藏。

https://jsfiddle.net/6zsdLa5p/

HTML:

<input type="checkbox" value="ui-options" /><br />
<input type="checkbox" value="ui-options" /><br />
<input type="checkbox" value="ui-options" /><br />
<input type="checkbox" value="ui-options" />

<br /><br />

<div class="ui-options">
show me!
</div>

CSS:

.ui-options {
display:none
}

JS:

$('input[type="checkbox"]').click(function(){
    if($(this).attr("value")=="ui-options"){
        $(".ui-options").slideToggle(150);
    }
});

【问题讨论】:

  • 你可以尝试去获取选中的数量,以知道你想隐藏/显示你的 div 使用这个: var someChecked = ($("input:checkbox[value=ui-options]:checked ").length>0) 告诉我没关系。

标签: jquery html onclick hide show


【解决方案1】:

使用切换,每次单击复选框时都会隐藏/显示 div。您需要检查是否有任何“选中”复选框并决定是否要显示或隐藏您的 div。比如这样:

$('input[type="checkbox"]').click(function(){
    if($('input[type="checkbox"]:checked').length > 0)
        $(".ui-options").slideDown(150);
    else
        $(".ui-options").slideUp(150);
});

【讨论】:

  • 你应该向他解释他做错了什么(或遗漏),以及你是如何解决的。 =)
【解决方案2】:

我建议:

// find the <input> elements whose type is equal to 'checkbox',
// bind a change event-handler to those elements:
$('input[type="checkbox"]').change(function() {

  // selecting the <div> element(s) with a class of
  // 'ui-options', then using a ternary within the square brackets,
  // if there are checked <input> elements, we use the slideDown
  // method (to show) if there are no checked <input> elements
  // we use the slideUp method (to hide):
  $('div.ui-options')[$('input[type=checkbox]:checked').length ? 'slideDown' : 'slideUp']('fast');
});

$('input[type="checkbox"]').change(function() {
  $('div.ui-options')[$('input[type=checkbox]:checked').length ? 'slideDown' : 'slideUp']('fast');
});
.ui-options {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="ui-options" />
<br />
<input type="checkbox" value="ui-options" />
<br />
<input type="checkbox" value="ui-options" />
<br />
<input type="checkbox" value="ui-options" />
<br />
<br />
<div class="ui-options">show me!</div>

外部JS Fiddle demo 用于实验。

参考资料:

【讨论】:

  • 好东西,感谢您的解决方案,还不知道“长度”:)
猜你喜欢
  • 2015-10-07
  • 1970-01-01
  • 1970-01-01
  • 2011-06-18
  • 2013-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多