Here is my modal html code:
-
The @JoshCrozier answer is good and useful but sometimes we need to Determine witch element triggered the modal to opened/closed AFTER it has been closed. (@Nomad has mentioned to this in the comments below the @JoshCrozier answer).
Also some times we need to determine which link or button in the body
or header
triggered the modal to close (not just buttons in the footer
).
Then i write this solution to mix @JoshCrozier and @Katia answers with my way and improve the final solution:
Add this part to Scripts of your page:
$('body').on('click','.modal .dismiss-modal', function() {
var closeRelatedTarget = this;
var $modal = $(closeRelatedTarget).closest('.modal');
$modal.one('hide.bs.modal hidden.bs.modal', function(event) {
$modal.data('closeRelatedTarget',closeRelatedTarget);
});
$modal.data('closeRelatedTarget','wait');
$modal.modal('hide');
});
$('body').on('show.bs.modal','.modal', function(event){
$(this).data('closeRelatedTarget','anElement');
$(this).data('showRelatedTarget',event.relatedTarget);
});
Now use it easily with simple Event Handlers or Get the target element:
● Determine witch element triggered the modal to show on show
and shown
(An embed Bootstrap feature):
$('#MyModal').on('show.bs.modal', function (event) {
console.log(event.relatedTarget);
});
and
$('#MyModal').on('shown.bs.modal', function (event) {
console.log(event.relatedTarget);
});
● Determine witch element triggered the modal to close on hidden
$('#BuyModal').on('hidden.bs.modal', function (event) {
if($(this).data('closeRelatedTarget')=='wait')
{return;}
console.log($('#MyModal').data('closeRelatedTarget'));
});
● Determine witch element triggered the modal to show even after the modal is closed
console.log($('#MyModal').data('showRelatedTarget'));
● Determine witch element triggered the modal to close even after the modal is closed
console.log($('#MyModal').data('closeRelatedTarget'));
Note: Instead of data-dismiss="modal"
property use my modal-dismiss
class to each element in the model that you can close the model and you want determine it (Don't use both modal-dismiss
class and data-dismiss="modal"
together).
Example: More info
Why? Because data-dismiss="modal"
close the model and trigger hide and hidden before we set closeRelatedTarget
.
- 热议问题