年月日Dropdowm Javascript

时间:2016-11-16 09:54:30

标签: javascript date dropdown leap-year

以下是根据月份和闰年调整天数的日期函数。出于某种原因,当选择2月时,它从不显示第28天是否是闰年。如果是闰年,它会从...跳出27,29当它不是闰年时它会在27结束。你可以帮忙解决这个bug?提前致谢

 <script type="text/javascript">
        // dropdown  date
        function monthOrYearChanged(yearId, monthId, dayId) {
            dayId = "#" + dayId;
            monthId = "#" + monthId;
            yearId = "#" + yearId;
            var currentMonth = $(monthId).val();
            var currentDay = $(dayId).val();

            // Set the numbers of days in the day dropdown
            changeDayCount = function (numDays) {
                while ($(dayId).children().length > numDays) {
                    $(dayId + " option:last").remove();
                }
                while ($(dayId).children().length < numDays) {
                    $(dayId).append($("<option></option>").attr(
                        "value",
                        $(dayId).children().length + 1).text($(dayId).children().length + 1));
                }
            };

            // Adjust number of days based on month and year
            switch (currentMonth) {
                case "4":
                case "6":
                case "9":
                case "11":
                    changeDayCount(30);
                    break;
                case "2":
                    var currentYear = $(yearId).val();
                    // Check for leap year
                    if (currentYear % 400 == 0 ||
                       (currentYear % 100 != 0 && currentYear % 4 == 0))
                        changeDayCount(29);
                    else
                        changeDayCount(28);
                    break;
                default:
                    changeDayCount(31);
            }

            // Make sure the day value wasn't too high
            if (currentDay > $(dayId).children().length)
                $(dayId).val($(dayId).children().length);
        }
    </script>

0 个答案:

没有答案