繁体   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