且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

测试元素是否已经有jQuery datepicker

更新时间:2023-11-28 23:47:58

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

  / *将类名添加到要指定已配置有日期选择器的元素。 * / 
markerClassName:'hasDatepicker',

所以我只需要测试 hasClass('hasDatepicker')。这似乎是最直接的方式。此外,此声明检查是否打开datepicker(对于任何有兴趣的人):

  if($(#ui -datepicker-div)。is(:visible)&& $(#ui-datepicker-div)。html()!=){
// datepicker is open。你需要第二个条件,因为它开始是可见但空的
}


I have a form with many input elements. Some are date fields with a jQuery UI datepicker alraedy attached:

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

Then I have a key command bound to this function:

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

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

This works great for elements which already have the datepicker on them. However any other fields will throw a javascript error. I'm wondering the best way to test to see if datepicker has already been initialized on that field.

Wow can't believe I missed this one. Line 108 of ui.datepicker.js:

/* Class name added to elements to indicate already configured with a date picker. */
markerClassName: 'hasDatepicker',

So I just need to test for hasClass('hasDatepicker'). This seems like the most straightforward way. Furthermore, this statement checks whether the datepicker is currently opened (for anyone who is interested):

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
}