【问题标题】:$(document).ready(function() interfering with datepicker display?$(document).ready(function() 干扰日期选择器显示?
【发布时间】:2016-03-11 16:36:54
【问题描述】:

我有一个日期选择器被修改为只显示月份和年份。有用。但是,当我添加$(document).ready(function() 来设置页面首次打开时的当前月份和年份时,只有左右箭头(下个月和上个月)选项可用(没有下拉菜单;没有其他按钮)。有什么问题?

JS:

$( document ).ready(function() {
  $("#datepicker").datepicker({dateFormat: 'MM yy'}).datepicker("setDate", new Date());
});

$(function() {
  $( "#datepicker" ).datepicker({
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: 'MM yy',
    onClose: function(dateText, inst) { 
      $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
    }
  });
});

HTML:

<input type="text" id="datepicker" name="datepicker" style="color: #595959;" onclick="function1();function2();" onchange="function3()" />

【问题讨论】:

  • 有,你可以使用你提供给datepicker()方法的对象的defaultDate参数。例如,请参阅我的答案。

标签: javascript jquery html jquery-ui datepicker


【解决方案1】:

问题是因为您在元素上定义了一个日期选择器,然后立即用另一个具有不同设置的实例覆盖它。如果您只想设置默认日期值,您可以在 datepicker 的单个实例上的单个 document.ready 处理程序中执行此操作。

另请注意,您的 onClose 设置是多余的,因为该代码块中的逻辑无论如何都是插件的默认行为。

试试这个:

$(function() {
    var defaultDate = new Date(); // = today

    $('#datepicker').datepicker({
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'MM yy',
        defaultDate: defaultDate, // set the default date of the picker
    }).datepicker('setDate', defaultDate); // set the text date value of the input

    // other code to run on document.ready...
});

Working example

【讨论】:

  • 我的错误。为您更新并添加了一个示例。
  • 现在工作!谢谢!
  • 没问题,很高兴为您提供帮助
猜你喜欢
  • 1970-01-01
  • 2010-12-11
  • 2011-04-01
  • 1970-01-01
  • 2011-05-22
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 2018-11-07
相关资源
最近更新 更多