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

WooCommerce商品分类归档描述展开/收起按钮点击后失效问题

修复WooCommerce分类归档描述Read more/Read less按钮失效问题

问题核心:初始创建的.read-more按钮绑定了点击事件,但后续动态生成的新.read-more没有绑定事件,导致仅第一次点击有效;另外代码里每次点击都新建按钮,容易产生冗余元素,且overflow属性设置错误(应为hidden而非none)。

修复方案:

  • 用事件委托处理动态生成的按钮点击事件,确保所有.read-more和.read-less按钮都能触发对应逻辑
  • 初始化时同时创建两个按钮,通过控制显示/隐藏来切换,避免重复创建元素
  • 修正overflow属性为hidden,确保超出内容被隐藏

修复后的代码:

jQuery(function ($) {
    $(document).ready(function () {
        // 获取描述容器原始高度
        const curHeight = $(".archive-description").height();
        // 初始化容器样式
        $(".archive-description").css({
            "height": "80px",
            "overflow": "hidden"
        });

        // 一次性添加两个按钮,初始只显示read-more
        $(".archive-description").after(`
            <button class='read-more'>Read more...</button>
            <button class='read-less' style='display:none;'>Read less...</button>
        `);
    });

    // 用事件委托处理read-more点击
    $(document).on('click', '.read-more', function () {
        $(".archive-description").animate({ height: curHeight });
        $('.read-more').hide();
        $('.read-less').show();
    });

    // 用事件委托处理read-less点击
    $(document).on('click', '.read-less', function () {
        $(".archive-description").animate({ height: 80 });
        $('.read-less').hide();
        $('.read-more').show();
    });
});

额外说明:

  • 使用const替代let存储固定的原始高度,更符合变量语义
  • 用模板字符串拼接按钮HTML,代码更易读
  • 初始隐藏.read-less按钮,通过show()/hide()切换状态,避免重复DOM操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 14:21:06