![](/img/trans.png)
[英]Flipping multiple divs by clicking different buttons using CSS/Javascript
[英]Slide different DIVs using different buttons but with the same ID with 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
),然后找到目標expandableSection
使用.closest()
或.parent()
因為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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.