如何在 jQuery 中隐藏正确的面板,其中有 2 个具有相同的类

How do I hide the proper panel in jQuery where there are 2 with the same class?

本文关键字:jQuery 隐藏      更新时间:2023-09-26

我试图一次只隐藏一个面板,具体取决于您单击的链接

这是用车把生成的html

<li>
    <a class="hide-me"><h3>Enterprise</h3></a>
    <ul class="sections">
            {{#each chart-container.[0].enterprise}}
                <li>
                    <a>
                        <span>
                            <img src="{{picture}}" />
                            {{name}} <br> {{role}}
                        </span>
                    </a>
                </li>
            {{/each}}
    </ul>
  </li>
  <li>
    <a class="hide-me"><h3>Consumer</h3></a>
    <ul class="sections">
            {{#each chart-container.[1].consumer}}
                <li>
                    <a>
                        <span class="name-role" id="{{id}}">
                            <img src="{{picture}}" />
                            {{name}} <br> {{role}}
                        </span>
                    </a>
                </li>
            {{/each}}
    </ul>
  </li>

这是jQuery

    $('.hide-me').on('click', function() {
      $('.sections').slideToggle();
    });

但显然它隐藏了那个班级,在这种情况下我该怎么办?

你需要找到你要找的那个。给定此结构,它看起来像:

var $li = jQuery(this).closest("li"); // Gets the parent li element
var $sections = $li.find(".sections"); // Within that li, finds the sections ul
$sections.slideToggle(); // Applies directly to this element

可能还有其他方法可以到达那里 - jQuery有很多方法可以达到DOM-但是我发现这很好而且很干净。

编辑

其他答案,使用 next ,应该工作正常 - 我避免它的原因是因为您可能会操纵列表的外观 - 也许将锚点移动到末尾而不是开头,或者在那里扔一个图像或其他东西 - 如果你这样做,你的代码将不再工作。我的方式是,只要你保持基本结构,不要把东西移到这个结构之外,你都很好。

根据显示的 html 使用next()

$('.hide-me').on('click', function() {
      $(this).next().slideToggle();
});