【问题标题】:jQuery logic for unclicked paragraphs未点击段落的 jQuery 逻辑
【发布时间】:2010-11-17 03:52:42
【问题描述】:

我有以下 html 结构。

<p class="expandableContent" ><span class="label">Computer and Laptop Repairs</span></p> <div style="clear: both;"> </div> <div class="services">content</div> <p class="expandableContent" ><span class="label">Softrware and Hardware</span></p> <div style="clear: both;"> </div> <div class="services">content2</div>

所以我重复了 content1 content2 content3 等。我正在编写一个切换功能,以便当我单击第一段时,第一个内容 div 会展开。当我单击第二段时,第二段会展开,但所有其他打开的内容都会折叠。

有人可以帮忙吗?

【问题讨论】:

    标签: jquery


    【解决方案1】:

    这应该对你有用:

    $(function() {
        $('.expandableContent').click(function() {
            $('.services').hide();
            $(this).nextAll('.services:first').show();
        });
    });
    

    首先,您将隐藏所有.services div,然后选择被点击段落之后的下一个,并展开它。

    这是一个实际的演示:http://jsfiddle.net/Ender/5nYpT/

    【讨论】:

      【解决方案2】:
      $('.expandableContent').click(function() {
          $('.services').hide();
          $('.services', this).show();
      });
      

      还将这些添加到您的 html 中:

      <div class="expandableContent">
        <p>....</p>
        <div style="clear:both;"></div>
        <div class="services">content</div>
      </div>
      

      【讨论】:

        【解决方案3】:

        您也可以在不修改 HTML 的情况下做到这一点。

        $(document).ready(function() {
            $('.services').hide();
            $('.expandableContent').click(function() {
                $('.services:visible').toggle();
                $(this).nextAll('.services:first').toggle();
            });
        });
        

        代码大部分应该是不言自明的。通过仅选择可见的 .services,我可以将它们切换为隐藏。然后,我使用 nextAll() 查找所有以下具有类 .services 的兄弟姐妹,但只取第一个。 (我不能使用 next() 因为它只接受紧随其后的兄弟,然后按类过滤它。不是我们想要的。)然后我在可见和隐藏之间切换。您可以在 http://jsfiddle.net/Lv2mW/ 找到一个工作示例。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-07-16
          • 2017-01-31
          • 2018-01-09
          • 1970-01-01
          • 1970-01-01
          • 2019-07-23
          • 1970-01-01
          相关资源
          最近更新 更多