【问题标题】:Need some help for this JavaScript code for DatePicker需要一些有关 DatePicker 的 JavaScript 代码的帮助
【发布时间】:2026-02-19 03:10:01
【问题描述】:

这是我的代码:

$(function() {
  $('#startDate').datepicker({
    dateFormat: "dd/mm/yy",
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    onClose: function(dateText, inst) {


      function isDonePressed() {
        return ($('#ui-datepicker-div').html().indexOf('ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all ui-state-hover') > -1);
      }

      if (isDonePressed()) {
        var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
        var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
        $(this).datepicker('setDate', new Date(year, month, 1)).trigger('change');

        $('.date-picker').focusout()
      }
    },
    beforeShow: function(input, inst) {

      inst.dpDiv.addClass('month_year_datepicker')

      if ((datestr = $(this).val()).length > 0) {
        year = datestr.substring(datestr.length - 4, datestr.length);
        month = datestr.substring(0, 2);
        $(this).datepicker('option', 'defaultDate', new Date(year, month - 1, 1));
        $(this).datepicker('setDate', new Date(year, month - 1, 1));
        $(".ui-datepicker-calendar").hide();
      }
    }
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script>
<input id="startDate" />

问题是我不知道为什么当我专注并回到它时日期会更改为一年的第一天。如果您在代码中发现错误,请告诉我。

jsfiddle

【问题讨论】:

  • 如果您删除了beforeShow 部分,则返回时日期不会更改
  • beforeShow 中的$(this).datepicker('setDate', new Date(year, month-1, 1)); 行是造成这种情况的原因。
  • 放警报(datestr);警报(年);警报(月);在适当的地方,你会看到

标签: javascript jquery jsp date datepicker


【解决方案1】:

感谢@depperm 在这部分的帮助,我发现了错误

month = datestr.substring(0, 2); 

修改为

month = datestr.substring(3, 5); 

【讨论】: