You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击show more按钮时如何仅展示当前点击div对应的动态分类内容

问题根源

你当前代码的问题有2处:

  1. JS选择器直接选中了全局所有div.card元素,点击任意show more按钮都会把所有分类下的卡片全部展开
  2. 循环输出分类容器时重复使用了id="parentId",ID属性全局唯一不可重复,会导致DOM选择异常

修复步骤

1. 调整PHP代码

修改循环内分类容器、show more按钮的输出逻辑,增加分类ID关联属性,同时修复重复属性问题:

// 原来的 echo '<div id="parentId">'; 替换成下面这行,绑定当前分类ID
echo '<div class="category-container" data-cat-id="'.$custom_term->term_id.'">';

// 原来的 <div class="col-lg-16 col-md-6 col-sm-12 col-xs-12" class="content"> 重复写了class属性,合并成:
<div class="col-lg-16 col-md-6 col-sm-12 col-xs-12 content">

// 原来的show more输出替换成下面这行,绑定当前分类ID
echo '  <div class="show-more" data-cat-id="'.$custom_term->term_id.'">Show more</div> ';

2. 替换JS逻辑

原来的全局选择器改成只选中当前点击按钮对应分类下的隐藏卡片:

$(document).ready(function(){
    $(".show-more").click(function(){
        // 拿到当前按钮绑定的分类ID
        const currentCatId = $(this).data('cat-id');
        // 只选中对应分类容器下的隐藏卡片展开
        $(`.category-container[data-cat-id="${currentCatId}"] .hide-block`).show();
        // 可选:展开后隐藏当前show more按钮,避免重复点击
        $(this).hide();
    });
});

如果需要实现点击切换展开/收起的效果,可以把JS改成:

$(document).ready(function(){
    $(".show-more").click(function(){
        const currentCatId = $(this).data('cat-id');
        const targetHideBlock = $(`.category-container[data-cat-id="${currentCatId}"] .hide-block`);
        targetHideBlock.toggle();
        // 切换按钮文本
        $(this).text(targetHideBlock.is(':visible') ? '收起' : 'Show more');
    });
});

内容的提问来源于stack exchange,提问作者Roberto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 11:09:02