我正在为我的网站构建过滤器侧边栏, 我希望能够通过按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>
我的问题是当我按下它关闭的列表时,我希望它保持打开状态。
答案 0 :(得分:4)
您应该为您的按钮提供课程并仅定位此课程:
$('.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;
答案 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>