侧栏 - 关闭并打开过滤器列表

时间:2018-05-31 16:26:45

标签: javascript jquery html

我正在为我的网站构建过滤器侧边栏, 我希望能够通过按btn打开和关闭过滤器列表。

jQuery('.parent > .children').parent().click(function() {
  jQuery(this).children('.children').slideToggle(200);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  <span>+</span>
  <ul class="children">
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>
<div class="parent">
  <span>+</span>
  <ul class="children">
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>
<div class="parent">
  <span>+</span>
  <ul class="children">
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>

我的问题是当我按下它关闭的列表时,我希望它保持打开状态。

2 个答案:

答案 0 :(得分:4)

您应该为您的按钮提供课程并仅定位此课程:

&#13;
&#13;
$('.toggler').click(function() {
  $(this).siblings('.children').slideToggle(200);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  <span class="toggler">+</span>
  <ul class="children">
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>
<div class="parent">
  <span class="toggler">+</span>
  <ul class="children">
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>
<div class="parent">
  <span class="toggler">+</span>
  <ul class="children">
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您需要检查实际li上是否发生了点击。

如果点击直接位于li元素上,请使用event.target执行任何操作,因此将其添加到点击处理程序中应执行此操作:

if ($(e.target).is('li')) return;

jQuery('.parent > .children').parent().click(function(e) {
  if ($(e.target).is('li')) return;
  jQuery(this).children('.children').slideToggle(200);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  <span>+</span>
  <ul class="children">
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>
<div class="parent">
  <span>+</span>
  <ul class="children">
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>
<div class="parent">
  <span>+</span>
  <ul class="children">
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>