jQuery Show/Hide nested divs

Deadly 提交于 2019-12-12 03:35:34

问题


I have awkward problem I cannot resolve.

I have a nested divs, which I want to show / hide when user clicks on a link. All divs at once.

I cannot assign ID's to my divs, so I will need to do it wiht classes.

<a href="#" id="showhide">Show more</a>

<div class="more">
<div class="more1">
<h2>Some title</h2>
<p>Some text</p>
</div>

<div class="more2">
<h2>Some title</h2>
<p>Some text</p>
</div>

<div class="more3">    
<h2>Some title</h2> 
<p>Some text</p>
</div>

</div>​

Here is the fiddle to my html structure. http://jsfiddle.net/56jdL/1/

Thanks!


回答1:


You can use first hide the div, using css:

.more { display: none }

or jQuery:

$('.more').hide() 

And then use toggle method:

$(function() {
   // $('.more').hide() 
   $('#showhide').click(function(e){
      e.preventDefault();
      $('.more').toggle()
   })
})

http://jsfiddle.net/J2YgE/




回答2:


Try this :

$("#showhide").on('click', function(){
    $(".more").children("div").slideToggle();
    return false;
});

DEMO

EDIT

To selectively toggle divs, give then a class by which they can be selected.

<div class="hideMe">
    ...
</div>

Then, the following jQuery will only act on those divs :

$("#showhide").on('click', function(){
    $(".more").children("div.hideMe").slideToggle();
    return false;
});

DEMO

EDIT 2

Here's a version that will work on your more complete code :

$(".showhide").on('click', function() {
    $(this).closest(".vrsticaoglas").find(".more").children("div").slideToggle();
    return false;
});

DEMO



来源:https://stackoverflow.com/questions/13797050/jquery-show-hide-nested-divs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!