prevent show event from firing when on datepicker

时光总嘲笑我的痴心妄想 提交于 2019-12-24 21:48:35

问题


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');
}


来源:https://stackoverflow.com/questions/40364286/prevent-show-event-from-firing-when-on-datepicker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!