您标记为正确的答案并不真正正确。让我分解一下。
$("#monthDate1").focus(function () {
$(".ui-datepicker-calendar").hide();
//add event to perform on done button click
$(".ui-datepicker-close").click(function(){
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$("#monthDate1").datepicker('option', 'defaultDate', new Date(year, month, 1));
$("#monthDate1").datepicker('setDate', new Date(year, month, 1));
});
});
通过执行$("#monthDate1").focus,每次您的控制进入focus 时,您都在参与click 事件,这非常糟糕。
考虑每次在$(".ui-datepicker-close") 上click 时启动$.ajax。您的函数将不会向服务器请求一次,而是与您的控制进入focus 一样多次。
修复:
不要在$("#monthDate1") 上绑定focus,而是使用live 或delegate(如果我没记错的话,对于jquery 版本>= 1.9.3)。
这是live 的示例:
$(".ui-datepicker-close").live('click', function(){
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$("#monthDate1").datepicker('option', 'defaultDate', new Date(year, month, 1));
$("#monthDate1").datepicker('setDate', new Date(year, month, 1));
});
这是delegate 的示例:
$("#ui-datepicker-div").delegate(".ui-datepicker-close", 'click', function(){
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$("#monthDate1").datepicker('option', 'defaultDate', new Date(year, month, 1));
$("#monthDate1").datepicker('setDate', new Date(year, month, 1));
});
更新
此更新来自我在评论中给出的回复。
在focus 事件中使用$(".ui-datepicker-calendar").hide(); 确实不太好,因为它有点小问题。
以下是你应该如何做到没有问题:
var dynamicStyle = $("<style> .ui-datepicker-calendar { display: none; } </style>")
.attr("id", "dynamicDatepickerStyle");
$("#monthDate1").datepicker({
beforeShow: function ()
{
$("body").append(dynamicStyle);
},
onClose: function ()
{
$("#dynamicDatepickerStyle").remove();
}
});
这将追加style,当你open时,datepicker将追加hidedatepicker,当datepicker关闭时,remove将追加style,以便它不会影响页面上的其他日期选择器。如果您想在页面上有多个日期选择器,有些带有calendar,有些没有。