2012-03-27 68 views
0

我正在嘗試並且未能將datepicker添加到動態創建的輸入。jQuery:在動態創建的輸入上運行多個日期選擇器

他們有不同的ID,我專門針對新的輸入和調用datepicker。

在下面的jsFiddle示例中,它僅適用於第二個輸入(第一個datepicker被調用),並且不適用於之後的任何其他輸入。

這裏是jsFiddle:http://jsfiddle.net/TJfbc/1/按加號加上更多。

注意:我知道第一個元素不會有datepicker。

回答

1

這裏有一個cleaner alternative

$(function() { 
    //append one handler to the parent to detect append actions 
    $('.action_items').on('click', '.expand', function() { 
     var $el = $(this); 
     $el.parent() 
      .clone() 
      .appendTo($el.closest('.action_items')) 
      .find('input') 
      .removeClass('hasDatepicker') 
      .each(function() { 
       newName = this.name.slice(0,6) + (parseInt(this.name.slice(6)) + 1); 
       this.name = newName; 
       this.id = newName; 
      }) 
      .datepicker(); 

     //change text, remove original handler, add the remove handler 
     $el.text('-').off('click').on('click',function(){ 
      $(this).parent().remove(); 
     }); 
    }) 
});​ 
+0

啊,這工作得很好謝謝你! – Craig 2012-03-28 07:19:26

0

http://jsfiddle.net/TJfbc/27/

你需要「刷新」先前的文本框是早已類的hasDatepicker'之前,你可以初始化一個新

new_action_item.find('.dpDate').removeClass('hasDatepicker').datepicker() 

可讀性的改善:

  • 不需要在new_action_item上重複調用$(),因爲clone()返回已經是jQuery的對象
+0

感謝您指出它需要「刷新」,我現在使用的摧毀它們:$(「 dpDate‘)日期選擇器(’摧毀」)添加新的前。 – Craig 2012-03-28 07:21:46

相關問題