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

Bootstrap Collapse在append()动态添加内容后无法展开

问题分析与解决方法

核心问题

你动态生成的折叠按钮data-target属性缺少#前缀,Bootstrap的Collapse组件要求data-target必须是带#的ID选择器,否则无法定位到对应的折叠面板。静态内容里你应该正确添加了#,所以功能正常,AJAX动态生成时遗漏了这个前缀。

修正步骤

  1. 补全data-target的#前缀
    把代码中按钮的data-target属性从:

    data-target="special-${specialPromotion.id}"
    

    修改为:

    data-target="#special-${specialPromotion.id}"
    
  2. (可选)兜底的事件委托方案
    若修正前缀后仍有问题,可通过事件委托绑定点击逻辑,确保动态添加的元素能触发折叠:

    $(document).on('click', '.promotion-details', function(e) {
      e.preventDefault();
      const target = $(this).data('target');
      $(target).collapse('toggle');
    });
    

修正后的完整代码片段

$.ajax({
    url: `${URL}/promotions/`,
    method: 'GET',
    dataType: 'json',
    success: function (response) {
        
        var promotions = response.promotions;
        var specialPromotions = filterByCategory(promotions, 'special');

        for (var i = 0; i < specialPromotions.length; i++) {
            var specialPromotion = specialPromotions[i];

            $('#special-contents').append(
                `<div class="col-md-6">
                    <div class="panel">
                        <div class="promotionBox promotionBox1">
                            <div class="promotionImage">
                                <img src="${specialPromotion.banner}">
                            </div>
                            <div class="promotionDesc promotionDesc1">
                                <p>${specialPromotion.title}</p>
                                <button data-category="Special" class="promotion-details btnShadow" type="button" data-toggle="collapse" data-target="#special-${specialPromotion.id}" aria-expanded="false">
                                    View Details
                                </button>
                                <a href="${specialPromotion.btn_link}" class="btnShadow" target="_blank">Visit</a>
                                <div id="special-${specialPromotion.id}" class="panel-collapse collapse ">
                                    <div class="panel-body">
                                        <div class="promotionDetailsContent">
                                            ${specialPromotion.content}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>`
            );
        }
        
        // 可选:手动初始化新添加的折叠组件
        $('.promotion-details').each(function() {
            $(this).collapse();
        });
    },
    error: function (error) {
        console.error('Error fetching promotions:', error);
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 08:05:14