【问题标题】:How to get consecutive elements using jquery?如何使用jquery获取连续元素?
【发布时间】:2012-02-25 06:02:08
【问题描述】:

请看下面的代码sn-p -

HTML

<div class="aclass">
   <h1>This is heading one</h1>
   <p>This is paragraph one, this will be hidden automatically</p>
   <p>This is paragraph two, this will be hidden automatically</p>
   <p>This is paragraph three, this will be hidden automatically</p>
   <h1>This is heading two</h1>
   <p>This is paragraph four, this will be hidden automatically</p>
   <p>This is paragraph five, this will be hidden automatically</p>
</div>

CSS

.aclass p {display:none;}

JS

$(document).ready(function(){
    $('.aclass h1').click(function(){
        $(this).next('p').toggle();
    });
});

当点击 h1 标签时,此 JS 代码会切换在 h1 标签之后显示单个 p 标签。但我需要切换连续 p 标签的显示(点击标题一时为一到三个)

执行此操作的 jQuery 代码应该是什么?

【问题讨论】:

  • 你应该将你的段落包装在一个 div 中,然后切换它。并不是说您的要求是不可能的,但它会比必要的复杂。

标签: jquery css-selectors


【解决方案1】:

使用.nextUntil:

$('.aclass h1').click(function() {
    $(this).nextUntil('h1', 'p').toggle(); // Selects all p tags after the h1
                                           // stops when it hits an h1
});​

演示:http://jsfiddle.net/dt7LH/

【讨论】:

    【解决方案2】:

    我为你拉小提琴:http://jsfiddle.net/hMsXz/2/

    这里是保存点击的代码:

     $('.aclass h1').click(function(){
        $(this).nextUntil('h1','p').toggle();
     });
    

    【讨论】:

    • 您可以将代码添加到您的答案中吗?此外,$(this).andSelf() 什么也不做,它将this 添加到集合中(其中已经包含this)。
    • 是的,我在“实验”中忘记了这一点,已经编辑过
    【解决方案3】:

    我猜你的意思是在点击&lt;h1&gt;下方展开/折叠所有&lt;p&gt;标签?

    使用nextUntil('h1') 选择直到&lt;h1&gt; 标记的所有兄弟元素。

    【讨论】:

      【解决方案4】:

      使用 jQuery 1.4 中引入的.nextUntil

      $(document).ready(function(){
         $('.aclass h1').click(function(){
             $(this).nextUntil('h1').toggle();
         });
      });
      

      【讨论】:

        猜你喜欢
        • 2018-07-29
        • 1970-01-01
        • 2021-08-01
        • 2012-07-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-01
        相关资源
        最近更新 更多