问题
I'm trying to create a menu with DIVs for Appetizers, Soups, etc. I use paragraph tabs as my toggler. All of my togglers have identical classes of "toggle". All of the DIV areas have the same class, "selection." How do I make it so when I click on a toggler, it just reveals the DIV class right above it. Sorry, my coding is messy.
JQuery:
$(document).ready(function(){
$('.toggle').click(function(){
$('.selection').slideToggle("slow");
});<br>
});
CSS:
.selection,.toggle
{
width: 700px;
margin-top: 0px;
margin-bottom: 0px;
margin-right: auto;
marign-lift: auto;
padding: 5px;
background: white;
border: solid 2px gray;
}
.toggle
{
text-align: center;
}
.selection
{
display: none;
text-align: left;
}
HTML:
<div class="selection">
Special Appetizer 8.95 <br>
Small Appetizer Plate 7.50
</div>
<p class="toggle">Appetizers</p>
<div class="selection">
Broccoli & Cream Soup $5.50 <br>
Clam Chowder 7.50
</div>
<p class="toggle">Soups</p>
<div class="selection">
Fried Rice 4.95 <br>
</div>
<p class="toggle">Rice</p>
回答1:
You can target an item relative to the one that was clicked on like this:
$(document).ready(function(){
$('.toggle').click(function(){
$(this).prev('.selection').slideToggle("slow");
});
});
This will get the clicked on .toggle
item and get the previous .selection
item and slideToggle just that one.
You can see it work here: http://jsfiddle.net/jfriend00/2zJ8z/
I would suggest improving it so you can click on the .selection item to make it go away as this makes toggling to explore with the mouse a little easier:
$(document).ready(function(){
$('.toggle').click(function(){
$(this).prev('.selection').slideToggle("slow");
});
$('.selection').click(function(){
$(this).slideToggle("slow");
});
});
You can see this minor enhancement here: http://jsfiddle.net/jfriend00/JrhNz/
If you want any other open ones to close when you open a new one, you could use this:
$(document).ready(function(){
$('.toggle').click(function(){
var prev = $(this).prev('.selection');
$(this).siblings('.selection').not(prev).slideUp("slow");
prev.slideToggle("slow");
});
$('.selection').click(function(){
$(this).siblings('.selection').slideUp("slow");
$(this).slideToggle("slow");
});
});
Demo of this option here: http://jsfiddle.net/jfriend00/JrhNz/6/
回答2:
I think you're looking for .prev():
$('.toggle').click(function(){
$(this).prev('.selection').slideToggle("slow");
});
来源:https://stackoverflow.com/questions/9642667/slidetoggle-on-one-div-instead-of-all-others-with-same-class