2011-04-26 145 views
3

我試圖將日期選擇器控件應用於克隆的輸入字段。 我在做的是找到我想要克隆的錶行,用克隆(假)克隆它,然後爲每個輸入帶一個類.date調用datepicker()。代碼如下:關於克隆元素的jquery datepicker

$('.repeat').bind('click', function(){ 
     var parentEl = $(this).parents('.root'); 
     var lastRow = jQuery.makeArray($(parentEl).find('.last')); 
     var newRow = $(lastRow).clone(false); 
     $(lastRow).removeClass('last'); 
     $(newRow).addClass('last'); 
     newRow.find('input').each(function(){ 
      this.name = this.name.replace(/\[(\d+)\]/,function(str,p1){return '[' + (parseInt(p1,10)+1) + ']'}); 
    }).end().insertAfter($(lastRow)); 

newRow.find('.date').each(function() { 
     $(this).removeAttr('id'); 
     $('.date').datepicker({dateFormat: 'dd-mm-yy', changeYear: true, yearRange: '1970:2010'}); 
      }); 

現在無論$(本).datepicker()和$( '日')日期選擇器()沒有附上日期選擇控件input.date。 上面的代碼按照預期工作,除了datepicker位。 有人有什麼想法?

在此先感謝!

+0

您是否曾嘗試在應用datepicker之前將它們附加到DOM? – 2011-04-26 10:49:12

+0

對不起,我的錯。有一些代碼沒有發佈,它在執行了一些格式化操作後,在lastRow(insertAfter($ lastRow))之後插入了newRow。我認爲那會把它附加到DOM上,還是我誤會了? – jimmy 2011-04-26 11:01:36

+0

確實會將它添加到DOM中。我發佈了一個答案,您需要對代碼進行額外的更改才能工作。 – 2011-04-26 11:07:54

回答

14

看來,如果你(應用日期選擇器前)加入該行第一,並刪除由日期選擇器.hasDatepicker添加類的工作。

$('.repeat').bind('click', function(){ 
     var parentEl = $(this).parents('.root'); 
     var lastRow = jQuery.makeArray($(parentEl).find('.last')); 
     var newRow = $(lastRow).clone(false, false); 
     $(lastRow).removeClass('last'); 
     $(newRow).addClass('last'); 
     $('.root').append(newRow); // added this 

     newRow.find('.date').each(function() { 
      $(this).removeAttr('id').removeClass('hasDatepicker'); // added the removeClass part. 
      $('.date').datepicker({dateFormat: 'dd-mm-yy', changeYear: true, yearRange: '1970:2010'}); 
     }); 
}); 

演示http://jsfiddle.net/gaby/LCfC2/

+2

Gaby,謝謝,您讓我的一天! removeClass()位做到了這一點。 從昨天開始,這一直困擾着我! 感謝您的幫助! – jimmy 2011-04-26 11:14:41

+0

這裏的關鍵是在創建元素上的日期選擇器之前刪除.hasDatepicker類。如果該類已經存在,日期選擇器將不會創建! – AJReading 2013-10-23 10:30:13

+0

謝謝!我從來沒有意識到,jQuery-ui的日期選擇器與這樣的元素ID搞混了:-S – Pabbles 2014-02-28 20:06:00

0

類元素必須被移除和日期選擇器必須被添加到該克隆元件。無論是否已附加到DOM,每次都適用於我。

$(inputData3).removeAttr("class"); 
$(inputData3).datepicker();