简体   繁体   中英

slideToggle <li> by using JS but without unique identifier

I have following HTML code and JS (coffescript) code that doesn't work as expected:

JS Code

$(document).ready ->
    $("#description_details").click ->
      $(this).closest('li').next().slideToggle("fast")

HTML Code (simple version)

<ul>
  <li><a href="#" id="description_details">Details</a></li>
  <li id="description_text">some more details</li>
  <li><a href="#" id="description_details">Details</a></li>
  <li id="description_text">some more details</li>
  <li><a href="#" id="description_details">Details</a></li>
  <li id="description_text">some more details</li>
  .
  .
  .
</ul>

CSS/SASS

#description_text
  display: none

My Intension is to toggle alway thes next li item, but it only works with the first one. I have no possibility to give an extra class or unique identifier to the li items. So I tried it with closest and next, but it only works with the first.

I also can't set the click event on the li the Link is in, because there is more text inside.

I would be very thankful for any help!

Hard truth: You can't have multiple ID's within your HTML markup. It's invalid and as a result, querying for it will only grab the very first occurence. Thats why you experience the behavior you explained.

You need to get rid of those multiple ID values. Either replace it by class names or find another way to correctly find / query for that <ul> element. Maybe by being more specific in a css selector , like "#mycontainer ul li a" .

as @97ldave mentioned you should have unique ID, you can not repeat it.

so change your ID to class then you can make use of the selector .description_details

http://jsfiddle.net/habo/pZKqy/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM