javascript - 嵌套按钮触发两次引导折叠事件
问题描述
我有一个collapse
包含多个其他collapse
元素的 Bootstrap 元素,当collapse
单击(显示或隐藏)时,我想捕获该事件。
我遇到的问题是,collapse
如果单击嵌套折叠按钮(对于父折叠和单击折叠),事件会被触发两次。
这是显示问题的演示:https ://jsfiddle.net/6nbsp9c1/2/
单击嵌套按钮时,事件被触发两次,我该如何解决?
解决方案
您需要使用stopImmediatePropagation来确保事件不会被多次调用。
Event 接口的
stopImmediatePropagation()
方法防止调用同一事件的其他监听器。
现场演示:
$(document).on('show.bs.collapse hide.bs.collapse', '.collapse', function(e) {
e.stopImmediatePropagation(); //use this
console.log('event triggered');
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
Link with href
</a>
<div class="collapse" id="collapseExample">
<div class="card card-body">
test test test
<a class="btn btn-primary" data-toggle="collapse" href="#collapseExample2" role="button" aria-expanded="false" aria-controls="collapseExample2">
Link with href
</a>
<div class="collapse" id="collapseExample2">
<div class="card card-body">
test test test
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
推荐阅读
- laravel - 如何在 Laravel 中创建目录
- excel - 删除包含 #N/A 的行
- java - RabbitMQ 中消息如何传递给消费者
- html - 通过 1 个按钮下载图像
- python - Keras 问题 -----> ValueError: Unknown layer:name
- python-3.x - 有没有办法打印在图像帧中找到的边界框的数量?
- c# - 有没有办法使用 c# 跟踪文件和文件夹并将其上传到 S3?
- node.js - 使用公牛的节点 cron 作业调度
- android - Apk 在发布模式下崩溃但在调试模式下完美运行
- swift - 使用按钮居中用户位置 - MapKit