隐藏/显示相关元素


Hide/Show related elements

所以,我有这段带有一些按钮和内容的代码。单击按钮时,我希望div 容器隐藏/显示。这是我使用的HTML代码的一部分:

<li>
   <input type="button" id="hideshow" class="showhide1" value="hide/show">
   <div id="content" class="showhide1" style="display: none;">Hello World</div>
</li>
<li>
   <input type="button" id="hideshow" class="showhide2" value="hide/show">
   <div id="content" class="showhide2" style="display: none;">Hello World</div>
</li>
And it goes on like maybe a 100 times O.o...

这是我使用的jQuery:

<script>
    jQuery(document).ready( function() {
         jQuery('#hideshow').live('click', function(event) {        
            jQuery('#content').toggle('hide');
         });
    });
</script>

这种代码有点有效,但所有按钮都隐藏/显示只有第一个内容div。我认为这是因为我在所有方面都有相同的ID。

但是我有不同的类,所以我想知道,我是否可以接受单击按钮的类,然后显示与按下按钮具有相同类的div 的内容。可以做到这一点还是有更好的方法?

首先.. 一如既往,ID 应该始终是唯一的...改用类。.并且live()已弃用on

无需更改大部分代码。

<script>
 jQuery(document).ready(function(){
 jQuery('ul').on('click','.showhide1,.showhide2', function(event) {        
     jQuery(this).next().toggle('hide'); //<--using next()
});
});

您也可以使用兄弟姐妹或最亲近,而不是下一个...

jQuery(this).siblings('.content').toggle('hide'); //<--using siblings()
jQuery(this).closest('.content').toggle('hide'); //<--using closest()

但是,您可以将相同的类添加到所有元素并使用类选择器

  jQuery('ul').on('click','.elementsClass', function(event) {        
     jQuery(this).next().toggle('hide');
  });

jsFiddle Demo

首先,您必须将 ID 更改为类,因为在 HTML 中 ID 应该是唯一的。

<li>
    <input type="button" class="hideshow showhide1" value="hide/show" />
    <div class="content showhide1" style="display: none;">Hello World</div>
</li>
<li>
    <input type="button" class="hideshow showhide2" value="hide/show" />
    <div class="content showhide2" style="display: none;">Hello World</div>
</li>

然后,您可以选择作为同级的内容div。

jQuery(document).ready(function(){
    jQuery('.hideshow').on('click', function(event) {        
        jQuery(this).siblings(".content").toggle('hide');
    });
});
  • P.S - 请注意,自 jQuery 1.7 以来,.live() 函数已被弃用,并在 jQuery 1.9 中删除。我改用.on()
<li>
<input type="button" id="hideshow" class="showhide" value="hide/show">
<div id="content" style="display: none;">Hello World</div>
</li>
<li>
<input type="button" id="hideshow" class="showhide" value="hide/show">
<div id="content" style="display: none;">Hello World</div>
</li>

这是你应该使用的jQuery:

<script>
    jQuery(document).ready(function(){
    jQuery('.showhide').on('click', function(event) {        
         $(this).next().toggle();
    });
    });
</script>