简体   繁体   English

单个功能可单独切换其他div内的多个div

[英]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. 我的页面上有一些div,每个div都有一个我想通过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. 依此类推...当然,这并不是最好的方法,总是在代码的同一部分重复div的名称。

HTML pattern: HTML模式:

<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')? 如何在不打开所有div并单击$('this')的情况下使其更短? - ps. -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: 您可以检查div是否具有特定的类值,例如:

 //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> 

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

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