Jquery UI Datepicker don't work after clone el

2019-07-29 07:30发布

问题:

I have a problem with cloning an element, the jQuery UI DatePicker does't work after cloning the element. Link to example: http://jsfiddle.net/V25qA/1/.

回答1:

You can't (safely) clone jQuery widgets - they have state that may not get copied.

You should call .datepicker('destroy') on the old element before you clone it, and then call .datepicker() again on the cloned input element to reinitialise it.



回答2:

It seems to be working fine for me in opera too.

In such cases try to delegate the event if you want this click event to work for newly created elements..

$('form').live('click', '.dpicker', function(){
     alert('clicked')
     $(this).datepicker().focus();  
});

Also I suggest you use .on() instead of .live() as .live is deprecated as of jquery version 1.7

DEMO



回答3:

Change the following line

$('.dpicker').eq(0).clone().prependTo('#new');

to

$('.dpicker').eq(0).clone().removeClass("hasDatepicker").prependTo('#new');

Then it will work.

Datepicker assigns 'hasdatepicker' class to an element when this element is datepicker-enabled via .datepicker();. If you clone this element, you also clone it's attributes. This is why datepicker plug-in does nothing when you call .datepicker();. If you remove this class datepicker will work as expected on the new element.