Toggle show\hide with jquery but with multiple ids

北城余情 提交于 2019-12-02 19:17:30

问题


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

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