切换同级元素jquery的可见性 [英] Toggle visibility of sibling element jquery

查看:80
本文介绍了切换同级元素jquery的可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在页面上有几个div.每个div都有一个标题,我可以单击该标题来切换相应div的可见性. div默认设置为display:none.

I have several divs on a page. Each div has a heading which I can click to toggle visibility of the corresponding div. The divs are set to display:none by default.

我在每个div的点击功能中都使用了#ids,但是由于我在同一页面上有多个div.我想使用一个.class,这样我就可以拥有一个类,从而可以控制可见性.

I have used #ids in the click functions of each of the divs , however since I have several divs on the same page. I would want to use a single .class so that I have a single class thus a single function that controls the visibility.

我猜我那时需要使用.parent.sibling类来做到这一点.

I am guessing i would then need to use .parent and .sibling classes to do this.

以下是我的代码的摘录: HTML:

Below is an excerpt from my code: HTML:

<div> 
    <legend>
        <a id="show_table" class="show_table" href="#">
            <span id="plus_minus"></span>Div
        </a>
    </legend>
    <div class="toshow" id="toshow">Div to be shown</div>
</div>

JS:

$('#show_table').click(function(){
    $("#toshow").slideToggle(); 
})

我想提高效率,这样我就不必使用#id对每个div进行此操作,我想知道如何使用单个.class,可能是.class的父级和同级做到这一点.

I would think to make this more efficient, so that I don't have to do this for every div using the #ids I would want to know how to use a single .class , probably parent and siblings of it to make this.

此外,我想在plus_minus跨度上具有减号/加号切换功能.我使用单独的ids进行了相同的工作.我怎么能用一个.class做到这一点.我尝试使用以下方法:

As an addition, I would like to have a minus/plus sign toggle functionality on the plus_minus span. I had the same working using the individual ids . How would I be able to achieve this using a single .class. I attempted this using below:

$('.div_show').click( function(){

$(this).parent().next().slideToggle();

if($(this).parent().next().is(':visible'){

$(this).closest('span').find('plus_minus').text('+');

}

else {

$(this).closest('span').find('plus_minus').text('-');

}


 });

但是似乎不起作用.

对如何实现此+/-切换功能的建议表示赞赏.

Suggestions on how to achieve this +/- toggle functionality appreciated.

推荐答案

为什么不试试这个

$('.show_table').click(function(){

    $(this).parent().next().slideToggle();

})

更新代码

因为您使用的是SlideToggle,所以对DOM的更改不易更新..因此,您必须处理其回调函数中的可见性问题.

Because you are using SlideToggle the changes to the DOM is not readily updated.. So you have to handle the visibility issues in the callback function of it..

尝试此代码

$('.show_table').click(function(){
      var $elem = $(this);
      $(this).parent().next().slideToggle('slow', function() {
          if($(this).is(':visible')){
             $elem.find('span').html('+');
          }
          else{
             $elem.find('span').html('-');
          }              
      });
})    

更新字段

这篇关于切换同级元素jquery的可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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