简体   繁体   中英

Show some divs when others are hidden with jQuery

I want, when a CATEGORY is active, for the .closeorshow div to be hidden. If no category is selected, the .closeorshow div should be shown.

I tested a bit with $(".closeorshow").hide() and .show() , but I am a jQuery beginner and I couldn't figure it out. The problem seems to be that the .closeorshow div reappears whenever I unselect any category, instead of when no categories are selected.

Here's a fiddle .

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:

$(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. This is done by calling $(".active") , which will produce an array, meaning it has access to the .length method. If the length of the array is greater than 0, you don't want to show .closeorshow , so call $(".closeorshow").hide() . Otherwise, you do want it shown, so call $("#.closeorshow").show() .

Tell me if everything isn't bueno.

fiddle

I only changed your 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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