【问题标题】:If check box is check display div but hide previous open div如果复选框选中显示 div 但隐藏之前打开的 div
【发布时间】:2015-08-27 13:57:31
【问题描述】:
<input type="checkbox" data-related-item="title1">
<span class="caption">Title</span>
<div class="hidden">
<h2>Title</h2>
<input type="text" id="title1">
<span class="caption">Lorem</span>
</div>
<hr>
<input type="checkbox" data-related-item="title2" checked>
<span class="caption">Title</span>
<div class="hidden">
<h2>Title</h2>
<input type="text" id="title2">
<span class="caption">Lorem</span>
</div>

Javascript

function evaluate(){
var item = $(this);
var relatedItem = $("#" + item.attr("data-related-item")).parent();

if(item.is(":checked")){
    relatedItem.fadeIn();
}else{
    relatedItem.fadeOut();   
}
}
$('input[type="checkbox"]').click(evaluate).each(evaluate);

这是关于这篇文章的:if check box is checked display div

我想问我如何使用此代码,但每次单击另一个复选框时,它都会隐藏前一个 div 并打开一个新的。一次只显示一个 div/内容,而不是同时显示两个。谢谢。

演示:http://jsfiddle.net/zgrRd/5/

【问题讨论】:

  • $('input[type="checkbox"]').click(evaluate).each(evaluate);这样做是为了在每个复选框上工作,而不是为特定的复选框调用它
  • 请编辑您的问题标题。标题应该是问题,而不是预期的结果
  • 这里有类似问题stackoverflow.com/questions/2650913/…你需要在选中另一个框时取消选中一个框,比如单选按钮。
  • 手风琴之类的? jqueryui.com/accordion

标签: javascript jquery html


【解决方案1】:

您必须使用change 而不是click 函数,并且在评估函数中,在开头添加以下行

$('input[type="checkbox"]').not($(this)).prop('checked',false).trigger('change');

在这里观看fiddle

【讨论】:

    【解决方案2】:

    如果我对您的理解正确,您一次只希望打开一个 &lt;div&gt;,这应该与一个复选框相关联。我的解释是,您一次也只选中复选框,因此所有其他复选框都需要取消选中。

    解决方案 1:使用单选按钮

    解决方案 2:取消选中所有复选框并重新选中当前复选框。

    显示&lt;div&gt;s 的解决方案是基于解决方案2。只需先隐藏所有&lt;div&gt;s,然后显示您的相关&lt;div&gt;。给你所有的&lt;div&gt;s 一个特定的类(例如class="toggling")或名称,用作关闭所有的选择器。

    $('input[type="checkbox"]').on("click", function() {
        var item = $(this);
        var relatedItem = $("#" + item.attr("data-related-item")).parent();
        $('.toggling').fadeOut(); //hide all
        relatedItem.FadeIn(); //show the current one
    });
    

    【讨论】:

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