简体   繁体   中英

Toggle the following selector

I have a bunch of elements like that

<h4>Question</h4>
<h5>Answer</h5>
<h4>Question2</h4>
<h5>Answer2/h5>

where I hide the answers by

h5{
display:none;
}

and display them again by

$( "h4" ).click(function() {
  $( "h5" ).slideToggle( "slow", function() {
  });
});

Of course that just toggles ALL h5-elements by clikcing ANY h4 and not the exactly following one. Therefore my question: How can I trigger the next following selector of a given species (like "h5" in that particular example).

Something like $(this > "h5" ).slideToggle(... didn't work out. But could that be sort of a solution?

Try below code

$("h4").click(function() { 
   $(this).next("h5").toggle(); 
});

You could give the h5 elements id's.

 $(function() { $("h5").toggle(); $("h4").click(function(e) { var answerSelector = '#' + $(this).data('answer-id'); $(answerSelector).toggle(); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h4 data-answer-id="a1">Question</h4> <h5 id="a1">Answer</h5> <h4 data-answer-id="a2">Question2</h4> <h5 id="a2">Answer2</h5> 

You could use the following for the first child

$("h4").click(function() {
  $(this).children("h5:first-child").slideToggle( "slow", function() {
     ...
  });
});

Or just this for all children h5 of the h4 element that was clicked.

$("h4").click(function() {
  $(this).children("h5").slideToggle( "slow", function() {
     ...
  });
});

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