2012-02-27 28 views
1

我有兩個不同ID和名稱的日期選擇器。我可以合併它們並刪除多餘的代碼嗎?如何合併兩個jQuery日期選擇器

 <script> 
    jQuery(function() { 
     jQuery("#<portlet:namespace/>other_date").datepicker({ 
      showOn: "button", 
      buttonImage: "/html/themes/control_panel/images/common/calendar.png", 
      buttonImageOnly: true, 
      changeMonth: true, 
      changeYear: true 
     }); 
     jQuery("#<portlet:namespace/>bene_relation_birth_date").datepicker({ 
      showOn: "button", 
      buttonImage: "/html/themes/control_panel/images/common/calendar.png", 
      buttonImageOnly: true, 
      changeMonth: true, 
      changeYear: true 
     }) 
}); 
</script> 

...

<input type="text" name="other_date" label="" value="" 
        id="other_date"></input> 


<input type="text" name="bene_relation_birth_date" label="" value="" 
        id="bene_relation_birth_date"></input> 

回答

1

您可以選擇一次,然後用.each()環比他們兩個元素。在循環中,將datepicker應用於您選擇的每個元素。您可以使用this關鍵字來訪問循環中的當前元素。

事情是這樣的:

var selector = "#other_date, #bene_relation_birth_date"; 

jQuery(selector).each(function(i, elm) { 
    jQuery(this).datepicker({ 
     showOn: "button", 
     buttonImage: "/html/themes/control_panel/images/common/calendar.png", 
     buttonImageOnly: true, 
     changeMonth: true, 
     changeYear: true 
    }); 
}); 
+0

::它的伎倆。 – 2012-02-27 11:37:26

+0

@oneofthelions太棒了! – 2012-02-27 11:38:26