如何在Bootstrap 4列表组项中嵌入两个独立触发模态框的链接
问题:Bootstrap 4列表组项内嵌套模态框触发冲突
在Bootstrap 4的列表组项中嵌入两个触发不同模态框的元素时,点击内部的信息图标会同时触发父列表项的模态框,导致两个模态框先后弹出。示例代码如下:
<button type="button" class="list-group-item list-group-item-action" data-id="123" data-toggle="modal" data-target="#membership-modal"> <span class="font-weight-bold">Peter Haworth</span> <a class="fa fa-info-circle text-secondary float-right" data-memberid="123" data-toggle="modal" data-target="#history-modal" data-name="Peter Haworth" style="font-size:20px;"></a><br> 1 year Individual, expiration 12/31/2023 </button>
解决方法
问题根源是事件冒泡:点击内部<a>标签时,点击事件会向上传递到父级<button>元素,导致两个模态框的触发逻辑都被执行。只需阻止内部元素的事件冒泡即可解决。
方法1:直接在元素上添加阻止冒泡的代码
给内部的信息图标<a>标签添加onclick="event.stopPropagation();"属性,阻止事件向上传递:
<button type="button" class="list-group-item list-group-item-action" data-id="123" data-toggle="modal" data-target="#membership-modal"> <span class="font-weight-bold">Peter Haworth</span> <a class="fa fa-info-circle text-secondary float-right" data-memberid="123" data-toggle="modal" data-target="#history-modal" data-name="Peter Haworth" style="font-size:20px;" onclick="event.stopPropagation();"></a><br> 1 year Individual, expiration 12/31/2023 </button>
方法2:使用jQuery绑定事件(适合批量处理)
如果页面中有多个类似的元素,可以用jQuery统一绑定阻止冒泡的逻辑:
$('.fa-info-circle').on('click', function(e) { e.stopPropagation(); });
这样点击信息图标时,只会触发#history-modal,不会触发父元素的#membership-modal。
内容的提问来源于stack exchange,提问作者Pete
相关产品推荐
相关产品推荐

