本文介绍了引导日期选择器,beforeShowDay在第二次单击后起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用bootstrap datepicker的 beforeShowDay 函数时遇到了一些问题.我的意图是当我单击任意一天时,所选日期之后的5天必须包含活动的课程.

I have some issues with beforeShowDay function with bootstrap datepicker. My intention is when I click any day, the 5 days after the selected day must contain the active class.

页面加载时,该功能可以正常运行.但是,当我尝试选择其他任何一天时,如果我希望该功能正常工作,则必须双击.该功能必须单击一下才能使用.有什么问题吗?

When the page loads, the function works perfectly. But when I try to choose any other day, I must double click if I want the function to work. The function must work with 1 click. Is something wrong?

var selectedDay = new Date().getTime();
$('.datepicker').datepicker({
    beforeShowDay: function (date) {
        var d = date.getTime();
        if (d > selectedDay && d < selectedDay + 1 + 86400000 * 5) {
            return {classes: 'active'};
        }
    },
    startDate: '0'
}).on('changeDate', function(e){
    selectedDay = e.date;
    selectedDay = selectedDay.getTime();
});

推荐答案

我知道这是一个古老的问题,但是自启动日期选择器至今仍在发生.原因是 beforeshowday changeDate 之前触发.因此,每次单击新的日期后, beforeshowday 都会先出现(带有旧日期),然后再发生 changeDate .不管我怎么看.我觉得这是他们应该修复的错误,因为样式应该与新日期一起使用.因此, changeDate 应该放在其他任何地方之前.

I know this is an old question but it's still happening today to bootstrap's datepicker. The reason is that the beforeshowday fires before the changeDate. So every time after you click a new day, the beforeshowday goes first (with the old date) then the changeDate happens afterwards. No matter how I look at it. I feel like this is a bug that they should fix, since the style should work with the new date. Thus the changeDate should go before anything else.

无论如何,解决方案实际上非常简单.更改日期后,只需在您的 changeDate 中强行执行 update ,它将使用新日期触发 beforeShowDay .这是我的代码段作为示例:

Anyway, the solution is in fact really simple. Just force a update in your changeDate after you change your date, and it will fire the beforeShowDay with the new date. Here is my code snippet as an example:

    $('#datepicker').datepicker({
        inline: true,
        todayHighlight: true,
        beforeShowDay:function hday(date){
            return (is_pay_day() && day_diff(date)<14 && day_diff(date)>0 ) ?  {classes: 'highlight'} : {} ;
        }
    }).datepicker('setDate', 'today').on("changeDate", function (ev) {
        //set the new date if one is selected
        (!ev.date) ? $(this).datepicker('setDate', selectedDate) : selectedDate = ev.date;
        $('#datepickerInput').val(selectedDate.toDateString());
        //force the update, so the beforeShowDay will be triggered
        $('#datepicker').datepicker('update',selectedDate);
    });

这篇关于引导日期选择器,beforeShowDay在第二次单击后起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 10:17