Bootstrap Collapse在append()动态添加内容后无法展开
问题分析与解决方法
核心问题
你动态生成的折叠按钮data-target属性缺少#前缀,Bootstrap的Collapse组件要求data-target必须是带#的ID选择器,否则无法定位到对应的折叠面板。静态内容里你应该正确添加了#,所以功能正常,AJAX动态生成时遗漏了这个前缀。
修正步骤
补全
data-target的#前缀
把代码中按钮的data-target属性从:data-target="special-${specialPromotion.id}"修改为:
data-target="#special-${specialPromotion.id}"(可选)兜底的事件委托方案
若修正前缀后仍有问题,可通过事件委托绑定点击逻辑,确保动态添加的元素能触发折叠:$(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
相关产品推荐
相关产品推荐

