ui.datepicker的回显问题
应用场景:
页面上有一些现有的输入框,需要调用日期插件,同时还要clone一份,动态添加到页面中,动态生成的输入框在调用datepicker的时候,click事件有效,但是选择的时间无法回显到对应的输入框中。
问题分析:
ui.datepicker.js 添加断点,发现datepicker.js 对 input 控件会自动生成一个id
/* Attach the date picker to a <a href="http://lib.csdn.net/base/jquery" class='replace_word' title="jQuery知识库" target='_blank' style='color:#df3434; font-weight:bold;'>jQuery</a> selection. @param target element - the target input field or division or span @param settings object - the new settings to use for this date picker instance (anonymous) */ _attachDatepicker: function(target, settings) { // check for settings on the control itself - in namespace 'date:' var inlineSettings = null; for (var attrName in this._defaults) { var attrValue = target.getAttribute('date:' + attrName); if (attrValue) { inlineSettings = inlineSettings || {}; try { inlineSettings[attrName] = eval(attrValue); } catch (err) { inlineSettings[attrName] = attrValue; } } } var nodeName = target.nodeName.toLowerCase(); var inline = (nodeName == 'div' || nodeName == 'span'); if (!target.id) target.id = 'dp' + (++this.uuid);
同时,在将 datepicker 附加到 input 控件的时候,如果发现input 控件有this.markerClassName 样式 ( markerClassName: 'hasDatepicker', 109行),则跳出function,不再进行附加。
/* Attach the date picker to an input field. */ _connectDatepicker: function(target, inst) { var input = $(target); inst.trigger = $([]); if (input.hasClass(this.markerClassName)) return; .... }
解决:
首先,将input 控件的id 自增1;然后,去掉 input 控件的'hasDatepicker' 样式:
$("input.clonedp").attr("id", ++$.datepicker.uuid).removeClass("hasDatepicker").datepicker({ showOn : "both" //,appendText : "(yyyy-mm-dd)" ,clearText : "Erase" ,mandatory : true //,closeText : "X" ,closeAtTop : false ,prevText : "Earlier" ,nextText : "Later" ,currentStatus: '<a href="http://lib.csdn.net/base/go" class='replace_word' title="Go知识库" target='_blank' style='color:#df3434; font-weight:bold;'>Go</a> to this month' //,monthNames:['一月','二月','三月','四月','五月','六月' // ,'七月','八月','九月','十月','十一月','十二月'] ,monthNames:['1','2','3','4','5','6','7','8','9','10','11','12'] ,yearRange : "2008:2010" ,dateFormat: 'yy-mm-dd' });