问题
I have a php page wich generates multiple ULs and a link above each UL, like this
<a title="Category one" id="cat-1"> Category one </a>
<ul id="subcategory-1-ul">
<li>Subcategory<li/>
<li>Subcategory</li>
<ul>
<a title="Category two" id="cat-2"> Category two </a>
<ul id="subcategory-2-ul">
<li>Subcategory<li/>
<li>Subcategory</li>
<ul>
Because there are many subcategories into each main categories I want to hide the ULs and only show them when I click the anchor.
I'm trying to use this jquery:
$(document).ready(function() {
$('#toggle-link').click(function() {
$('#ul-to-hideshow').toggle('slow');
});
})
This works ok but only for the first UL and an anchor with the same id. I need to modify it somehow to pass the id of each UL or anchor and toggle each UL on and off. I have unique ID for each anchor and its UL.
How do I modify the script ?
回答1:
Use .each or use a common class to hide them;
$('.ULCategory').toggle('slow');
So your html might then be;
<a title="Category one" id="cat-1"> Category one </a>
<ul class="ULCategory" id="subcategory-1-ul">
<li>Subcategory<li/>
<li>Subcategory</li>
<ul>
edit based on comment
<a title="Category one" id="cat-1"> Category one </a>
<ul class="cat-1" id="subcategory-1-ul">
<li>Subcategory<li/>
<li>Subcategory</li>
<ul>
$('.cat-1').toggle('slow');
来源:https://stackoverflow.com/questions/19039282/toggle-show-hide-with-jquery-but-with-multiple-ids