使用滑动不同的按钮,不同的DIV但用javascript
问题描述:
相同的ID我有以下脚本:使用滑动不同的按钮,不同的DIV但用javascript
$(document).ready(function() {
$('.expandButton').click(function() {
$('.expandableSection').toggle("slide");
});
});
我想将它应用到多个部分。问题是每次点击.expandButton按钮时,所有部分都会滑动,而不是使该特定部分滑动。这是有道理的,但我需要的是只有该部分滑动。
我的部分是这样的:
<h1 class="expandButton"></h1>
<div class="expandableSection">
</div>
<h1 class="expandButton"></h1>
<div class="expandableSection">
</div>
<h1 class="expandButton"></h1>
<div class="expandableSection">
</div>
答
使用基于上下文查找的expandableSection
元素。在你的情况下,目标expandableSection
是点击expandButton
元素的父,所以你可以使用this
(这指的是点击button
),然后使用.closest()
或.parent()
找到目标expandableSection
(因为expandableSection
是按钮的直接父)
$(document).ready(function() {
$('.expandButton').click(function() {
$(this).next('.expandableSection').toggle("slide");
});
});
.expandButton {
height: 20px;
background: lightgrey;
}
.expandableSection {
height: 20px;
background: lightblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1 class="expandButton"></h1>
<div class="expandableSection">
</div>
<h1 class="expandButton"></h1>
<div class="expandableSection">
</div>
<h1 class="expandButton"></h1>
<div class="expandableSection">
</div>
答
你可以试试这个:
$('.expandButton').click(function() {
$(this).parent().toggle("slide");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="expandableSection">
<h1 class="expandButton">sdfsdf</h1>
</div>
<div class="expandableSection">
<h1 class="expandButton">dsfsdfs</h1>
</div>
<div class="expandableSection">
<h1 class="expandButton"> sfasdas</h1>
</div>
<div class="expandableSection">
<h1 class="expandButton">sdfsdf</h1>
</div>
+0
对不起,我在解释中犯了一个错误。每个h1都在每个开放div之前,因此div不再是h1的父级...任何解决方案?现在更新问题 – samyb8 2014-12-19 14:39:54
不适用于我。只要我添加$(this).closest或.parent,什么都不会发生 – samyb8 2014-12-19 14:31:23
@ samyb8查看更新 – 2014-12-20 02:04:30