youngxu 发表于 2013-1-29 09:02:27

jQuery UI datepicker选择日期后,日期层会再次加载

在项目中,一同事使用jQuery UI的datepicker日期控件时,出现以下问题:
1、在IE浏览器下,选择好日期后,datepicker的日期显示会重新加载;
2、在Firefox浏览器下,选择好日期后,datepicker的日期显示不会重新加载,可是想再次修改日期时,焦点必须离开输入的日期框后,再点击进入才能出现datepicker的日期选择框。

针对上述出现的问题,我对jQuery UI 1.8.15版本的源码进行了查看,发现jquery.ui.datepicker是由focus事情来显示日期选择层的,经检查代码发现_selectDate方法中默认的选择日期是选择日期赋值给输入框后,再重新对输入框设定focus。这样在IE浏览器下就会出现日期选择框重新加载了。

问题代码出现在jquery.ui.datepicker.js文件的909到930行,其具体如下:
/* Update the input field with the selected date. */_selectDate: function(id, dateStr) {var target = $(id);var inst = this._getInst(target);dateStr = (dateStr != null ? dateStr : this._formatDate(inst));if (inst.input)inst.input.val(dateStr);this._updateAlternate(inst);var onSelect = this._get(inst, 'onSelect');if (onSelect)onSelect.apply((inst.input ? inst.input : null), );// trigger custom callbackelse if (inst.input)inst.input.trigger('change'); // fire the change eventif (inst.inline)this._updateDatepicker(inst);else {this._hideDatepicker();this._lastInput = inst.input;inst.input.focus(); // restore focusthis._lastInput = null;}},

   将上面“inst.input.focus(); // restore focus”的代码注释掉后,进行测试。发现上述出现的两个问题都能解决,因此决定修改jQuery UI的代码。

    通过代码研究发现,上述遇到的问题,应该也可以通过自定义onSelect方法来实现。只是简单试了下,效果没达到,所以就冒险对jQuery UI的代码进行修改了。

    项目中引用的jQuery UI是min的js文件,也就是jQuery UI团队发布的,经过压缩后的文件。该文件和源码存在很大差别。主要区别有:
    1、源码文件是分plugin来定义单个js文件的;
    2、jquery-ui-1.8.15.custom.min.js文件是将所有发布的ui,集成在一个文件里;
    3、jquery-ui-1.8.15.custom.min.js文件的代码经过了压缩。

    不过还好,jquery-ui-1.8.15.custom.min.js文件的压缩主要是针对定义的变量进行的。经datepicker、_selectDate和focus()一路查找下来。终于找到了a.input.focus();这句代码。将其删除后,测试后达到了解决效果。
页: [1]
查看完整版本: jQuery UI datepicker选择日期后,日期层会再次加载