问题
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