单个功能可以单独切换其他div中的多个div [英] Single function to toggle multiple divs inside other divs individually

查看:123
本文介绍了单个功能可以单独切换其他div中的多个div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网页上有一些div,每个div都有我想要通过jQuery切换的内容。
这实际上是我的代码的样子:

  $('。my_div')。click(function() {
$(.my_div_B).slideToggle(slow);
});
$ b $('。my_div2')。click(function(){
$(.my_div_B2).slideToggle(slow);
});
$ b $('。my_div3')。click(function(){
$(.my_div_B3).slideToggle(slow);
});

等等......当然,这不是最好的方法,重复名称这些div始终在代码的相同部分。



HTML模式:

 < div class =my_div> 
< img />
< img />
< div class =my_div_B>文字< / div>
< / div>

如何在不打开所有我的div点击$('this')的情况下将其缩短?
- ps。我知道有一些类似的问题,但答案似乎是特定于该标记。

您可以检查div是否存在具体的类值如下:

//选择具有class属性的div,以my_div开头$('div [class ^ =my_div]') .click(function(){//使用class start查找子元素div my_div_B $(this).children(div [class ^ ='my_div_B'])。slideToggle(slow);});

 < script src =https://ajax.googleapis.com &aaax / libs / < 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>  

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>

这篇关于单个功能可以单独切换其他div中的多个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆