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
2 Answers
Reset to default 3You 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');
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745375963a4625000.html
评论列表(0条)