jQuery .each()切换隐藏元素 [英] JQuery .each() to toggle hidden elements

查看:238
本文介绍了jQuery .each()切换隐藏元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于JQuery来说是新手,并且难以理解.each()。

Very new to JQuery, and am struggling to understand .each().

我希望能够单击任何标题,并在下面添加段落该标题出现,然后消失。目前,我只能切换第一段。

I would like to be able to click on any heading, and have the paragraph under that heading appear, and then disappear. At the moment, I can only get the first paragraph to toggle.

我的代码是:

<script>
$(document).ready(function(){
  $("h2").click(function(){
    $("#hidden").each(function(){
        $(this).toggle();      
    });
  });
});

</script>

<h2>HEADING 1</h2>
<div id="hidden" style="display:none">
<p>paragraph 1</p>
</div>

<h2>HEADING 2</h2>
<div id="hidden" style="display:none">
<p>paragraph 2</p>
</div>

非常感谢您的帮助!

推荐答案

ane元素的ID必须是唯一的使用类属性才能将相似的元素分组

ID of ane element must be unique use class attribute to group similar elements

<h2>HEADING 1</h2>
<div class="hidden" style="display:none">
<p>paragraph 1</p>
</div>

<h2>HEADING 2</h2>
<div class="hidden" style="display:none">
<p>paragraph 2</p>
</div>

然后也无需使用each循环,您可以在选择器$('。hidden')

then also there is no need to use a each loop, you can call .toggle() in the jQuery wrapper returned by the selector $('.hidden')

$(document).ready(function(){
  $("h2").click(function(){
    $('.hidden').toggle();      
  });
});

更新未读完整的问题问题似乎是如何切换下一个div

Update Didn't read the complete question the question seems to be how to toggle the next div

$(document).ready(function(){
  $("h2").click(function(){
    $('.hidden').hide();
    $(this).next().toggle();      
  });
});

演示:小提琴

这篇关于jQuery .each()切换隐藏元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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