测试元素是否已经有jQuery datepicker

mac*_*ca1 40 javascript jquery jquery-ui datepicker

我有一个包含许多输入元素的表单.一些是附加了jQuery UI datepicker alraedy的日期字段:

$("#someElement").mask("9?9/99/9999").datepicker({showOn: 'button', buttonText:'Click here to show calendar', duration: 'fast', buttonImageOnly: true, buttonImage: /images/calicon.gif' });
Run Code Online (Sandbox Code Playgroud)

然后我有一个绑定到此函数的键命令:

function openCalendar() {
    var selection = document.activeElement;

    // { Need to test here if datepicker has already been initialized 
        $(selection).datepicker("show");
    // }
}
Run Code Online (Sandbox Code Playgroud)

这适用于已经有日期选择器的元素.但是任何其他字段都会抛出一个javascript错误.我想知道最好的方法来测试是否已经在该字段上初始化了datepicker.

mac*_*ca1 69

哇不敢相信我错过了这个.ui.datepicker.js的第108行:

/* Class name added to elements to indicate already configured with a date picker. */
markerClassName: 'hasDatepicker',
Run Code Online (Sandbox Code Playgroud)

所以我只需要测试一下hasClass('hasDatepicker').这似乎是最直接的方式.此外,此语句检查datepicker当前是否已打开(对于任何感兴趣的人):

if ($("#ui-datepicker-div").is(":visible") && $("#ui-datepicker-div").html() != "") {
    // datepicker is open. you need the second condition because it starts off as visible but empty
}
Run Code Online (Sandbox Code Playgroud)

  • 为了检查是否初始化了jQuery UI自动完成,我使用了这个:`$('#myinput').is(':data(autocomplete)')`.我认为这也适用于datepicker. (7认同)

Raf*_*ael 12

1)如果代码在尝试打开日期选择器时抛出错误,您可以将代码放入try..catch

2)初始化datepicker时,可以将一些数据设置到输入字段

$("#someElement").data("datepicker-initialized", true);
Run Code Online (Sandbox Code Playgroud)

3)您可以使用datepicker插件存储的数据

if($("#someElement").data("datepicker") != null){
   // datepicker initialized
}
Run Code Online (Sandbox Code Playgroud)

要么

if($.data($('#someElement').get(0), 'datepicker')){
   // datepicker initialized
}
Run Code Online (Sandbox Code Playgroud)

4)datepicker内部使用函数_getInst

if($.datepicker._getInst($('#someElement')[0]) != null){}
Run Code Online (Sandbox Code Playgroud)

该方法与示例3几乎相同.

找不到更好的解决方案.