Need help calling a JQuery function more than once without having to give every selector a function

StackOverflow https://stackoverflow.com/questions/16888478

  •  30-05-2022
  •  | 
  •  

Okay so essentially I am creating a top ten list to be used multiple times on a site. However I want the contents of the list to be hidden and revealed one by one when clicking on the number. However, clicking on the first number causes the whole list to expand. Here is the JQuery:

    $(document).ready(function(){
       $("#articletext h2").click(function(){
          $(".revealTitle").fadeIn();
          $(".revealText").slideDown();
  });
});

Here is the HTML:

<h2>10. <span class="revealTitle">The Title To Fade In On Click</span></h2>

<span class="revealText">The Text to Slide Down On Click</span>

So what I want it to do is:

  • When the number (i.e 10.) is clicked, only that numbers revealTitle and revealText comes up.
  • Similarly when the next number is clicked (i.e 9.) 9.'s revealTitle and revealText come up.

Thanks In Advance.

有帮助吗?

解决方案

Use context Selector

This will make sure only the elements with .revealText and .revealTitle are searched within the current context (Which here is the h2 element that was clicked)

 $(".revealTitle", this).fadeIn();
 $(this).nextAll(".revealText").first().slideDown();

其他提示

use $(this) selector and find method to target the correct children:

$(document).ready(function(){
    $("#articletext h2").click(function(){
          $(this).find(".revealTitle").fadeIn();
          $(this).find(".revealText").slideDown();
    });
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top