简体   繁体   English

如果复选框是复选框,则显示div但隐藏先前打开的div

[英]If check box is check display div but hide previous open div

<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 Java脚本

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);

This was about this post: if check box is checked display div 这与帖子有关: 如果选中复选框,则显示div

I would like to ask how do I use this code but every time you click another checkbox it hides the previous div and opens a new one. 我想问一下我如何使用此代码,但是每次单击另一个复选框时,它都会隐藏上一个div并打开一个新的div。 Just showing one div/content at a time instead of showing both open. 一次只显示一个div /内容,而不是同时显示两个div /内容。 Thanks. 谢谢。

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

You must use change instead of click function and inside evaluate function, add the following line at the start 您必须使用change而不是click函数,并在评估函数中,在开始处添加以下行

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

Watch here fiddle 在这里观看小提琴

If I understand you correctly, you want only one <div> open at a time, which should correlate to a checkbox. 如果我对您的理解正确,那么您一次只希望打开一个<div> ,这应该与一个复选框相关。 I interpret this, that you also only checkbox checked at a time, so all other checkboxes wold need to be unchecked. 我的解释是,您一次也只选中一个复选框,因此所有其他复选框都需要取消选中。

Solution 1: Use radio buttons 解决方案1:使用单选按钮

Solution 2: Uncheck all checkboxes and re-check the current one. 解决方案2:取消选中所有复选框,然后重新选中当前复选框。

The solution for showing the <div> s is based on solution 2. Just hide all <div> s first and then show your related <div> . 显示<div>的解决方案基于解决方案2。只需先隐藏所有<div> ,然后再显示相关的<div> Give all your <div> sa certain class (eg class="toggling" ) or name to be used as a selector for closing all. 给所有<div>一个特定的类(例如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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM