-->

bootstrap modal and datepicker show events

2019-06-17 04:57发布

问题:

When click on datepicker (http://www.eyecon.ro/bootstrap-datepicker/), his SHOW event fires, but the modal's SHOW.BS.MODAL fires too. Whhere is a problem?

$(document).ready(function() {
$('#ArrDate')
.datepicker()
.on("show", function(event){
    alert("Q");
});

$("#dlg3000to3100")
.on('show.bs.modal', function (event) {
    alert("W");
});

$("#dlg3000to3100")
.modal("show");
});

exampleExample

Thanks

回答1:

It seems to be a bug (or feature?) of the datepicker. What you can do is to prevent the show.bs.modal event reaching the dialog.

$('#ArrDate').on('show.bs.modal', function (event) {
    event.stopPropagation();
});

This will detect the event at the datepicker level and stop the event propagation, so show.bs.modal will not 'bubble up' to the dialog.



回答2:

Another work around is to swap the show.bs.modal with shown.bs.modal on modal event.

modal.on('shown.bs.modal', function (event) {
               // Do something
            });

however if it is not possible to swap show with shown or hide with hidden use the namespace check

modal.on('show.bs.modal', function(e) {
    if (e.namespace === 'bs.modal') {
         // Do something
    }

});



回答3:

Had a similar issue, caused by the datepicker watching for a show event.

One option is to use the shown event on the modal but this is not ideal in all cases

$('#dlg3000to3100').on('shown.bs.modal', function (event) {
    // modal code in here
});

A more elegant solution is to check the namespace of the event

$('#dlg3000to3100').on('show.bs.modal', function (event) {
    if(event.namespace !== 'bs.modal') return;
    // modal code in here
});

https://jsfiddle.net/bzh75tww/