[英]How to open/close a bootstrap modal without triggering event?
I have a bootstrap modal that trigger additional actions when opened or closed manually. 我有一个引导模式,当手动打开或关闭时会触发其他操作。 These actions are hooked with
show.bs.modal
and hide.bs.modal
events. 这些动作与
show.bs.modal
和hide.bs.modal
事件挂钩。
Now I want to also be able to open or close modal programmatically without triggering this action. 现在,我还希望能够以编程方式打开或关闭模态而无需触发此操作。 Is it possible?
可能吗?
You need a way of determining how the modal was triggered; 您需要一种确定触发方式的方式。 a flag or similar.
旗帜或类似的东西。
According to the Bootstrap documentation (assuming you're using version 3), e.relatedTarget
is set as the element which was clicked for the show.bs.modal
event in your callback. 根据Bootstrap文档 (假设您使用的是版本3),将
e.relatedTarget
设置为在回调中针对show.bs.modal
事件单击的元素。 Thus, e.relatedTarget
is undefined if triggered programmatically. 因此,如果以编程方式触发,则
e.relatedTarget
是未定义的。 You can use this to avoid your show.bs.modal
callback function from running. 您可以使用它来避免
show.bs.modal
回调函数运行。 For example: 例如:
$('#myModal').on('show.bs.modal', function (e) {
if (e.relatedTarget) {
// User triggered, do something...
}
});
As for the hide.bs.modal
event, there isn't a similar attribute available, but you could achieve the same effect with a toggle class or data attribute. 至于
hide.bs.modal
事件,没有类似的属性可用,但是您可以通过使用切换类或数据属性来实现相同的效果。 Set this flag just before you're about to hide your modal in your code, and ensure that your modal's hide.bs.modal
callback is checking for its presence, and only run if not present. 在即将在代码中隐藏模式之前,请设置此标志,并确保模式的
hide.bs.modal
回调正在检查其是否存在,并且仅在不存在的情况下运行。 For example: 例如:
// Prep modal event
$('#myModal').on('hide.bs.modal', function (e) {
if (!$('#myModal').hasClass('programmatic')) {
// User triggered, do something...
}
});
// When hiding your modal
$('#myModal').toggleClass('programmatic');
$('#myModal').modal('hide');
For both of the above cases, another option is to remove your event listener before showing/hiding, trigger the modal to be shown/hidden, and re-add the event listener. 对于上述两种情况,另一个选择是在显示/隐藏之前删除事件侦听器,触发要显示/隐藏的模式,然后重新添加事件侦听器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.