为什么我的某些代码执行两次?

时间:2019-10-31 20:12:13

标签: jquery

我正在编写使用JQuery和HTML&CSS制作日历的代码。当我运行此代码时,它做了什么,但是我的日期填写了两次,因此我在同一日历页面中两次输入了1-31。这在我整个项目的更多代码中都在发生,我不明白为什么。

let createCalendarHTML = function () {
    var date_picker_element = $('.date-picker');
    var selected_date_element = $('.date-picker .selected-date');
    var dates_element = $('.date-picker .dates');

    var mth_element = $('.date-picker .dates .month .mth');
    var next_mth_element = $('.date-picker .dates .month .next-mth');
    var prev_mth_element = $('.date-picker .dates .month .prev-mth');

    var days_element = $('.date-picker .dates .days');
    var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    var days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

    var date = new Date();
    var day = date.getDate();
    var month = date.getMonth();
    var year = date.getFullYear();

    var selected_date = date;
    var selected_day = day;
    var selected_month = month;
    var selected_year = year;

    mth_element.text(months[month] + ' ' + year);

    selected_date_element.text(formatDate(date));

    populateDates();

    $(next_mth_element).on('click', function () {
        month++;
        if (month > 11) {
            month = 0;
            year++;
        }
        mth_element.text(months[month] + ' ' + year);
    });
    $(prev_mth_element).on('click', function () {
        month--;
        if (month < 0) {
            month = 11;
            year--;
        }
        mth_element.text(months[month] + ' ' + year);
    });

    function formatDate(d) {
        var day = d.getDate();
        if (day < 10) {
            day = '0' + day;
        }
        var month = d.getMonth() + 1;
        if (month < 10) {
            month = '0' + month;
        }
        var year = d.getFullYear();
        return day + '/' + month + '/' + year;
    }

    function populateDates(e) {
        for (var i = 0; i < days_per_month[month]; i++) {
            days_element.append($("<div class='day'></div>").text(i+1));
        }
    }
};
return {
    init: init,
    openCalendar: openCalendar,
    createCalendarHTML: createCalendarHTML
};

0 个答案:

没有答案