【问题标题】:jQuery UI datepicker onChangeMonthYear and the inst parameterjQuery UI datepicker onChangeMonthYear 和 inst 参数
【发布时间】:2011-09-12 12:56:11
【问题描述】:
$('.selector').datepicker({
   onChangeMonthYear: function(year, month, inst) { ... }
});

如何使用 onChangeMonthYear 的 'inst' 参数自动选择当月的第一天?

见:http://jsfiddle.net/sD8rL/

我目前正在使用下面的代码,但我觉得我应该能够以更直接的方式使用“inst”变量。

   $(".datepicker" ).datepicker({
      changeMonth: true,
      changeYear: true,
      maxDate:0,
      onChangeMonthYear: function(year, month, inst){
        // set date to 1st on year or month change

        // this seems  bit janky, but works
        $('#' + inst.id).datepicker( "setDate", month + '/1/' + year );

        // Can't I use the instatnce to set the date?

        // $(inst).datepicker( "setDate", month + '/1/' + year ); // fails
        // inst.datepicker( "setDate", month + '/1/' + year ); // fails
        // inst.selectedDay = 1; // fails
        // inst.currentDay = 1; // fails 
      }
  });

【问题讨论】:

    标签: jquery-ui datepicker


    【解决方案1】:

    如果没有特别的原因要使用inst,您可以随时使用this

      onChangeMonthYear: function(year, month, inst){
         $(this).datepicker( "setDate", month + '/1/' + year );
      }
    

    查看实际操作:http://jsfiddle.net/william/sD8rL/2/

    【讨论】:

    • 这完全有道理,我真的没有任何特别的理由使用“inst”,“this”效果很好。
    【解决方案2】:

    William Niu 的解决方案不考虑其他日期格式(例如 dd-mm-yyyy)。 你最好从你的 datepicker 中获取一个 Date 对象,并按照你喜欢的方式修改它(即设置一个月的第一天)。修改后,您可以将修改后的 Date 对象重新传递给您的日期选择器。

        dateFormat: "dd-mm-yy",
        onChangeMonthYear: function(year, month, inst){
          var selectedDate = $(this).datepicker( "getDate" );//Date object
          selectedDate.setDate(1);//set first day of the month
          selectedDate.setMonth(month-1);//month is 1-12, setMonth is 0-11
          selectedDate.setFullYear(year);
          $(this).datepicker( "setDate", selectedDate );
       }
    

    这样您就不会覆盖日期格式(可能在日期选择器初始化期间设置);)

    注意月份格式:datepicker处理月份的格式是1-12,而Date对象是0-11。

    希望对你有帮助,再见!

    【讨论】:

      猜你喜欢
      • 2021-06-08
      • 1970-01-01
      • 2010-11-08
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多