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

javascript - Bootstrap modal on shown method run multiple times - Stack Overflow

programmeradmin3浏览0评论

I use twitter bootstrap modals's js to show and hide a modal:

$('#myModal').modal('show')//show
$('#myModal').on('shown', function () {
// do something…
})
$('#myModal').on('hidden', function () {
// do something…
})

....
$('#myModal').modal('hide')//hide

My problem is when show and hide modal multiple times, the code in //do something... run multiple times. I guess that's because every time i show a modal, it listen to shown and the function run 5 times when the modal hide and open 5 times, any way to prevent this?


Using the way fco suggested below did solve the shown problem, but unfortunately the hide does not work, i.e. still execute more than one times, one thing different, i hide the dialog using the data-dismiss="modal" markup, not through js.

Any ideas?

I use twitter bootstrap modals's js to show and hide a modal:

$('#myModal').modal('show')//show
$('#myModal').on('shown', function () {
// do something…
})
$('#myModal').on('hidden', function () {
// do something…
})

....
$('#myModal').modal('hide')//hide

My problem is when show and hide modal multiple times, the code in //do something... run multiple times. I guess that's because every time i show a modal, it listen to shown and the function run 5 times when the modal hide and open 5 times, any way to prevent this?


Using the way fco suggested below did solve the shown problem, but unfortunately the hide does not work, i.e. still execute more than one times, one thing different, i hide the dialog using the data-dismiss="modal" markup, not through js.

Any ideas?

Share Improve this question edited Apr 11, 2013 at 5:11 Mike asked Apr 10, 2013 at 16:52 MikeMike 3,57511 gold badges47 silver badges70 bronze badges 2
  • Do you think your problem is similar to stackoverflow./questions/15706342/… – Farid Rn Commented Apr 10, 2013 at 17:06
  • You need to unbind the shown function if you only want it to execute the first time. – adamdehaven Commented Apr 10, 2013 at 18:08
Add a ment  | 

2 Answers 2

Reset to default 3

You should use one instead of on

The .one() method is identical to .on(), except that the handler is unbound after its first invocation. For example:

$('#myModal').modal('show')//show
$('#myModal').one('shown', function () {
// do something…
})
$('#myModal').one('hidden', function () {
// do something…
})

....
$('#myModal').modal('hide')//hide

check out .off()

if you want the event handler to run only the first time you need to do something like:

function myHandler() {
    //your event handling code here
    $('#myModal').off('show', myHandler);
}
$('#myModal').on('shown', myHandler);
$('#myModal').modal('show');
//...
$('#myModal').modal('hide');
发布评论

评论列表(0)

  1. 暂无评论