簡體   English   中英

jQuery切換按鈕切換所有div而不是單個所需的div

[英]jQuery toggle button is toggling all divs instead of the single desired one

我有幾個“新聞卡”div,他們都被按鈕切換。 我需要切換按鈕所在的“新聞卡”的“cardexpand”。

PS。 這是我在這個網站上的第一個問題所以請原諒任何不愉快的事情。

<script>
    $(document).ready(function(){
        $(".cardexpand").hide();
        $(".expand").click(function(){
            $(this).next(".cardexpand").toggle(1000);
        });
    });
</script>

<div class="newscard">
    <img src="news1.jpg" class="img">
    <div class="cardbody">
        <p class="cardtitle">James Blyat does not associate with Vainglory players</p>
        <p class="carddetails">Mar 29, 2019 • Gaming</p>
        <button class="expand">Expand</button>
    </div>
    <div class="cardexpand">
        <hr class="cardhr"></hr>
        <p class="cardtext">
            Vainglory is just anime of the gaming world and is 
            for weebs, he says. Vainglory is just anime of the gaming world and is 
            for weebs, he says.
        </p>
    </div>
</div>

next()函數不起作用,因為該button不是您要切換的容器的兄弟。 您必須先選擇父級。 嘗試這個:

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $(".cardexpand").hide(); $(".expand").click(function(){ $(this).parent().next(".cardexpand").toggle(1000); }); }); </script> <div class="newscard"> <img src="news1.jpg" class="img"> <div class="cardbody"> <p class="cardtitle">James Blyat does not associate with Vainglory players</p> <p class="carddetails">Mar 29, 2019 • Gaming</p> <button class="expand">Expand</button> </div> <div class="cardexpand"><hr class="cardhr"></hr> <p class="cardtext">Vainglory is just anime of the gaming world and is for weebs, he says. Vainglory is just anime of the gaming world and is for weebs, he says. </p> </div> </div> <div class="newscard"> <img src="news1.jpg" class="img"> <div class="cardbody"> <p class="cardtitle">James Blyat does not associate with Vainglory players</p> <p class="carddetails">Mar 29, 2019 • Gaming</p> <button class="expand">Expand</button> </div> <div class="cardexpand"><hr class="cardhr"></hr> <p class="cardtext">Vainglory is just anime of the gaming world and is for weebs, he says. Vainglory is just anime of the gaming world and is for weebs, he says. </p> </div> </div> 

你可以用

$(this).closest(".newscard").find(".cardexpand").toggle(1000);

這里, nearest()搜索“向上DOM樹”,直到找到匹配的元素。 從那里,我們使用find()在找到的元素內搜索匹配.cardexpand元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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