简体   繁体   中英

Single function to toggle multiple divs inside other divs individually

I have some divs in my page, and each one of them has got a content I want to toggle via jQuery. This is actually how my code looks like:

$('.my_div').click(function() {
   $( ".my_div_B" ).slideToggle( "slow" );
 });

$('.my_div2').click(function() {
   $( ".my_div_B2" ).slideToggle( "slow" );
 });

$('.my_div3').click(function() {
   $( ".my_div_B3" ).slideToggle( "slow" );
 });

and so on... of course it's not the best way to do that, repeating the name of the divs always in the same part of code.

HTML pattern:

<div class="my_div">
<img />
<img />
<div class="my_div_B">text</div>
</div>

How can I make it shorter without opening ALL my divs clicking on $('this')? - ps. I know there are some similar questions, but the answers seem to be specific for that markup.

You can check if div has specific class value like:

 //select div with class attribute starts with my_div $('div[class^="my_div"]').click(function() { //find child element div with class start my_div_B $(this).children("div[class^='my_div_B']").slideToggle("slow"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="my_div"> <img src='http://placehold.it/200x100' /> <img src='http://placehold.it/200x100' /> <div class="my_div_B">text</div> </div> <div class="my_div2"> <img src='http://placehold.it/200x100' /> <img src='http://placehold.it/200x100' /> <div class="my_div_B2">text</div> </div> 

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