简体   繁体   English

切换以下选择器

[英]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. 当然,只需单击任何h4即可切换所有h5元素,而不是紧随其后的元素。 Therefore my question: How can I trigger the next following selector of a given species (like "h5" in that particular example). 因此,我的问题是:如何触发给定种类的下一个选择器(在特定示例中为“ h5”)。

Something like $(this > "h5" ).slideToggle(... didn't work out. But could that be sort of a solution? 像$(this>“ h5”).slideToggle(...没办法。但这可以解决吗?

Try below code 试试下面的代码

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

You could give the h5 elements id's. 您可以指定h5元素的ID。

 $(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元素的所有子h5进行此操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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