簡體   English   中英

使用不同的按鈕滑動不同的DIV,但使用Javascript具有相同的ID

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM