最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to openclose a bootstrap modal without triggering event? - Stack Overflow

programmeradmin1浏览0评论

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.

Now I want to also be able to open or close modal programmatically without triggering this action. Is it possible?

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.

Now I want to also be able to open or close modal programmatically without triggering this action. Is it possible?

Share Improve this question asked Jan 31, 2016 at 10:58 maxime schoenimaxime schoeni 2,8872 gold badges22 silver badges21 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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. Thus, e.relatedTarget is undefined if triggered programmatically. You can use this to avoid your show.bs.modal callback function from running. 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. 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. 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.

发布评论

评论列表(0)

  1. 暂无评论