-->

prevent show event from firing when on datepicker

2019-09-06 14:09发布

问题:

I have a bootstrap datepicker. I want the show event to be fired when the input box is first clicked. However I don't want the event to be fired if the user is traversing through the months with the prev and next arrows.

Is this possible?

$('#sandbox-container input').datepicker({
    autoclose: true
});

$('#sandbox-container input').on('show', function(e){
    console.log('show event');
});

If you run the fiddle you will see the message get logged when you first click the input field (I want that behavior). however you will also see that message displayed if you use the prev and next arrows.

JS Fiddler is here - http://jsfiddle.net/LcqM7/611/

回答1:

You will need to check if the show already "run" in the current "state".

$('#sandbox-container input')
    .on('show', function(e){
        if (! $(this).data('showrun')) {
            console.log('show event');
            $(this).data('showrun', true);
        }
    })
    .on('hide', function(e){
      $(this).data('showrun', false);
    })
    .on('changeMonth', function(e){
        console.log('change month event');
    });

And a working example:
http://jsfiddle.net/k6b3yepb/



回答2:

It's a bit grim but you can leverage the hide event to unbind the show then reattach it using jqueries one.

http://jsfiddle.net/5dhkumko/

$('#sandbox-container input').datepicker({
    autoclose: true
});

$('#sandbox-container input').one('show', showMethod);

$('#sandbox-container input').on('hide', function(e) {
    $('#sandbox-container input').off('show', showMethod).one('show', showMethod);
});

function showMethod() {
    console.log('show event');
}