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

jQuery仅对第一个元素生效,隐藏元素无法触发展开收起

问题分析与解决方案

核心问题点

  1. 重复ID冲突:循环生成多个id="show-more",HTML规范中ID必须唯一,这会导致只有第一个匹配的元素能绑定点击事件,其他元素的点击完全无效。
  2. 事件绑定范围错误:直接给#show-more绑定点击事件,对于动态生成或切换显示的元素,这种静态绑定方式无法生效,应该用事件委托绑定到父级稳定元素上。
  3. 全局文本修改错误:点击按钮时用$('#show-more').html()修改所有按钮文本,会导致所有展开按钮同步变化,不符合需求。

修复后的代码

var target = $('.button_img_custom_class .buttonSelectionItemContainer');
$(target).each(function () {
    $(this).toggleClass("example");
    var items = $(this).children().length;

    if (items > 6) {
        $(this).css({'max-height': '115px', 'overflow': 'hidden'});
        // 把ID换成类名,避免重复
        $(this).after('<a class="show-more">Show More</a>');
    }
});

// 使用事件委托,绑定到父级稳定元素(也可以换成更接近的父容器)
$(document).on('click', '.show-more', function () {
    var $container = $(this).prev();
    if ($container.hasClass('open')) {
        $container.removeClass('open');
        // 只修改当前点击的按钮文本
        $(this).html('Show More');
        $container.css({'max-height': '115px'});
    } else {
        $container.addClass('open');
        $(this).html('Show Less');
        $container.css({'max-height': '1000px'});
    }
});

关键修改说明

  • 将id="show-more"改为class="show-more",确保每个按钮的标识唯一且符合HTML规范。
  • 用$(document).on('click', '.show-more', function(){})实现事件委托,不管元素是动态生成还是切换显示,点击事件都能正常触发。
  • 操作当前点击的按钮时,用$(this)指代,只修改当前按钮的文本,避免影响其他按钮。
  • 移除了无用的item_length变量,代码中未用到该变量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 09:57:49