简体   繁体   中英

jQuery show() hide() with nested levels

I'm having a bit of an issue showing / hiding the next sublevel in a tree that I've generated. I think this scenario is different from the other questions posted here, and could use a bit of help. I can get the next levels to show, but clicking on the previous level to close the current level is proving tricky. I've tried all sorts of combinations of parent() , next() , find() , closest() , is(':visible') , and they all seem to interact with the other nodes on the tree - rather than the current one. For example, here's the display

Folder 1
   Folder 1 Subfolder
      Folder 1 subfolder level 2
Folder 2
   Subfolder 1
   Subfolder 2
      Subfolder 2 sublevel

<div class="subfolder">
<a  href="#">Folder 1</a>
 <div class="subfolder">
    <a  href="#">Folder 1 Subfolder</a>
    <div class="subfolder">
        <a  href="#">Folder 1 subfolder level 2</a>
    </div>
  </div>
</div>
<div class="subfolder" title="This is the second folder">
<a href="#">Folder 2</a>
<div class="subfolder" title="">
    <a href="#">Subfolder 1</a>
</div>
<div class="subfolder" title="">
    <a href="#">Subfolder 2</a>
    <div class="subfolder">
        <a href="#">Subfolder 2 sublevel</a>
    </div>
  </div>
</div>

To complicate things, I'm showing the first sublevels initially, using

//Show first sublevel folders for each parent
$subFolder.each(function () {
    var $this = $(this);
    $this.find('.subfolder .subfolder').hide();

});

So, I can get the second level sublevels to show using

//show subfolders when parent is clicked, and hide details pane on any subfolder click
$subFolder.click(function () {
    $(this).children('div.subfolder').show();

});

But using $(this).children('div.subfolder').hide(); obviously doesn't do the trick to hide them.

Basically, I'm looking for an interaction, that will hide both "Folder 1 Subfolder" and "folder 1 subfolder level 2" when Folder 1 is clicked. Is such a thing even possible using the above html structure?

Here's what I last ended up with that's in the ballpark, but still doesn't do the job

 $subFolder.click(function () {
    $(this).children('div.subfolder').show();
    if ($(this).find('.subfolder').is(':visible')) {
     $(this).find('.subfolder').stop().hide();
     }
     if ($(this).find('.subfolder').is(':hidden')) {
     $(this).next().find('.subfolder').stop().show();
     }
});

is this what you are looking for? I changed some class names

$(".folder a").click(function () {
    $(this).siblings('.subfolder').slideToggle();
});

$(".subfolder a").click(function () {
    $(this).siblings('.innerfolder').slideToggle();
});

**** UPDATE * ***

I used your original class names

JSFIDDLE

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