[英]Show some divs when others are hidden with jQuery
I want, when a CATEGORY is active, for the .closeorshow
div to be hidden. 我希望当CATEGORY处于活动状态时,要隐藏
.closeorshow
div。 If no category is selected, the .closeorshow
div should be shown. 如果未选择类别,则应显示
.closeorshow
div。
I tested a bit with $(".closeorshow").hide()
and .show()
, but I am a jQuery beginner and I couldn't figure it out. 我用
$(".closeorshow").hide()
和.show()
进行了一些测试,但我是jQuery的初学者,我无法弄清楚。 The problem seems to be that the .closeorshow
div reappears whenever I unselect any category, instead of when no categories are selected. 问题似乎是,每当我取消选择任何类别而不是未选择任何类别时,
.closeorshow
div就会重新出现。
HTML: HTML:
<ul class="types">
<li class="item" data-target="games">Games</li>
<li class="item" data-target="music">Music</li>
<li class="item" data-target="movies">Movies</li>
<li class="item" data-target="ljudobild">Ljud & Bild</li>
</ul>
<div class="description" id="games">Description of Games</div>
<div class="description" id="music">Description of Music</div>
<div class="description" id="movies">Description of Movies</div>
<div class="description" id="ljudobild">Description of Television</div>
<br><br>
<div class="closeorshow">
This class are going to be SHOWN when NONE of the items are selected, and HIDED
when one of the items is selected.
</div>
JS: JS:
$(document).ready( function() {
$('.types li').click( function(t) {
$('.closeorshow').hide();
if ($(this).hasClass('active')) {
$(this).removeClass('active');$(this).addClass('item');
$('.closeorshow').show();
} else {
$(this).addClass('active');$(this).removeClass('item');
}
$('#'+$(this).attr('data-target')).toggle();
});
});
The basic idea is to check whether the class .active
exists. 基本思想是检查类
.active
是否存在。 This is done by calling $(".active")
, which will produce an array, meaning it has access to the .length
method. 这是通过调用
$(".active")
,它将生成一个数组,这意味着它可以访问.length
方法。 If the length
of the array is greater than 0, you don't want to show .closeorshow
, so call $(".closeorshow").hide()
. 如果数组的
length
大于0,则不希望显示.closeorshow
,因此请调用$(".closeorshow").hide()
。 Otherwise, you do want it shown, so call $("#.closeorshow").show()
. 否则,您确实希望显示它,因此调用
$("#.closeorshow").show()
。
Tell me if everything isn't bueno. 告诉我一切是否都没有。
I only changed your JavaScript: 我只更改了您的JavaScript:
$(document).ready(function () {
$('.types li').on("click", function () {
$(this).toggleClass("active item");
$('#' + $(this).attr("data-target")).toggle();
if ($(".active").length === 0)
$(".closeorshow").show();
else
$(".closeorshow").hide();
});
});
Here's the fiddle made originally to demonstrate the same concept. 这是最初为演示相同概念而制作的小提琴 。 Only keeping for reference since it's simpler than your problem, but nevertheless demonstrates how to fix the problem in question.
仅作参考之用,因为它比您的问题更简单,但是仍然展示了如何解决有问题的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.