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

javascript - Show event for all Bootstrap Modals on the page - Stack Overflow

programmeradmin2浏览0评论

I'm trying to do something (in this case some statistics) whenever a Bootrap modal is opened.

I know, I can ad an event listener like this to a modal:

$('#modal-content').on('shown.bs.modal', function() {
   alert('do something');
});

But is there a way to have a listener for all modals on the page? Bonus question: even for those who are inserted by Javascript?

I have thought about something like this:

jQuery('.modal[role="dialog"]').on('show.bs.modal', function() {
   alert('do something');
});

But I hope that there's a better way and something that will work for modals that are inserted by Javascript.

I'm trying to do something (in this case some statistics) whenever a Bootrap modal is opened.

I know, I can ad an event listener like this to a modal:

$('#modal-content').on('shown.bs.modal', function() {
   alert('do something');
});

But is there a way to have a listener for all modals on the page? Bonus question: even for those who are inserted by Javascript?

I have thought about something like this:

jQuery('.modal[role="dialog"]').on('show.bs.modal', function() {
   alert('do something');
});

But I hope that there's a better way and something that will work for modals that are inserted by Javascript.

Share Improve this question asked Feb 19, 2015 at 16:15 wawawawa 5,0845 gold badges35 silver badges59 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 12

This ought to do the trick for you--it catches the event when it bubbles up to the document level, so that should catch them all:

$(document).on('shown.bs.modal', function() {
   alert('do something');
});

See this bootply

HTH, -Ted

If you know the ids ahead of time, you could just list them out:

$('#modalOne, #modalTwo').on('shown.bs.modal', function() {
   alert('do something');
});

Or better yet, if you are creating them programmatically as well as in html and are using a mon prefix for the id, you can use the following:

$("div[id^='modal']").on('shown.bs.modal', function() {
   alert('do something');
});
发布评论

评论列表(0)

  1. 暂无评论