如何修改Popover内按钮样式?点击切换类无效问题求助
Popover内按钮类切换失效的解决方案
问题原因
你当前的代码中,Popover的内容是从隐藏的#popover-baseline元素复制HTML生成的——Bootstrap会基于这段HTML字符串创建全新的DOM元素插入页面,而你写的Q1_BClick()函数操作的是原来隐藏的那个按钮,不是Popover里显示的新按钮,所以类切换的操作根本没作用在可见元素上,自然看不到效果。
解决方案(推荐事件委托方式)
这种方式不需要修改内联onclick属性,还能兼容动态生成的元素,代码更简洁:
- 先修改HTML,去掉按钮的
onclick属性:
<button data-toggle="popoverB" id="bookmarkB" style="background:#0070c0; border: 0px !important; color:white;" data-placement="bottom" title="Quarter Selection"> <i class="fa fa-bookmark bookmarkIcon"></i> </button> <div id="popover-baseline" style="display:none;"> <div class="row" style="height: 25px;margin: 0px;"> <div class="col-3" style=" padding-left: 5px; height:100%;"> <button id="btn_Q1_B" class="dashboardViews-btn dashboardViews-btnActive" style="height:100%; width:46px;"> Q1 </button> </div> <div class="col-3" style=" padding-left: 5px; height:100%;"> <button id="btn_Q2_B" class="dashboardViews-btn dashboardViews-btnActive" style="height:100%; width:46px; margin-left:3px;"> Q2 </button> </div> <div class="col-3" style=" padding-left: 5px; height:100%;"> <button id="btn_Q3_B" class="dashboardViews-btn dashboardViews-btnActive" style="height:100%; width:46px; margin-left:5px;"> Q3 </button> </div> <div class="col-3" style=" padding-left: 5px; height:100%;"> <button id="btn_Q4_B" class="dashboardViews-btn dashboardViews-btnActive" style="height:100%; width:46px; margin-left:7px;"> Q4 </button> </div> </div> </div>
- 修改JavaScript代码,用事件委托绑定点击事件,同时优化Popover初始化逻辑(避免每次点击都重复初始化):
// 只初始化一次Popover $('#bookmarkB').popover({ content: $('#popover-baseline').html(), html: true, placement: 'bottom', trigger: 'click', sanitize: false, id: 'popover_baseline' }); // 事件委托:监听文档中Popover内所有季度按钮的点击 $(document).on('click', '#popover_baseline .dashboardViews-btn', function() { // 直接切换当前点击按钮的active类 $(this).toggleClass('dashboardViews-btnActive'); });
备选方案(Popover显示后绑定事件)
如果一定要保留内联逻辑,可以在Popover显示完成后,给新生成的按钮重新绑定事件:
// 初始化Popover $('#bookmarkB').popover({ content: $('#popover-baseline').html(), html: true, placement: 'bottom', trigger: 'click', sanitize: false, id: 'popover_baseline' }); // Popover显示完成后,给内部按钮绑定事件 $('#bookmarkB').on('shown.bs.popover', function() { $('#popover_baseline #btn_Q1_B').click(function() { $(this).toggleClass('dashboardViews-btnActive'); }); $('#popover_baseline #btn_Q2_B').click(function() { $(this).toggleClass('dashboardViews-btnActive'); }); $('#popover_baseline #btn_Q3_B').click(function() { $(this).toggleClass('dashboardViews-btnActive'); }); $('#popover_baseline #btn_Q4_B').click(function() { $(this).toggleClass('dashboardViews-btnActive'); }); });
效果展示

内容的提问来源于stack exchange,提问作者TerribleDog
相关产品推荐
相关产品推荐

