首页 > 解决方案 > jQuery 切换按钮切换所有 div 而不是单个所需的

问题描述

我有几个“新闻卡”div,它们都可以通过按钮切换。我只需要切换按钮所在的“新闻卡片”的“卡片扩展”。

附言。这是我在这个网站上的第一个问题,所以请原谅任何不愉快的事情。

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

标签: javascriptjqueryhtml

解决方案


你可以使用

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

在这里,closest()搜索“DOM 树”直到找到匹配的元素。从那里,我们使用find()在找到的元素中搜索匹配的元素.cardexpand


推荐阅读