2013-02-08 41 views
0

我有一個允許用戶選擇3個日期時間段(或1或2)的表單。 重複此模式,允許用戶爲自定義範圍,每週,每月,每天等選擇日期。 如果有辦法我可以優化jquery,這樣我就不必寫出每個輸入的整個jquery函數? 唯一真正改變的是id中的數字。jquery通過日期選擇器的類似記錄循環

<input type='text' id='custom1from'><input type='text' id='custom1until'> 
<input type='text' id='custom2from'><input type='text' id='custom2until'> 
<input type='text' id='custom3from'><input type='text' id='custom3until'> 

<input type='text' id='monthly1from'><input type='text' id='monthly1until'> 
<input type='text' id='monthly2from'><input type='text' id='monthly2until'> 
<input type='text' id='monthly3from'><input type='text' id='monthly3until'> 



$("#custom1from").click(function() { 
     $("#custom1from").datepicker(); 
     }); 

     $("#custom1until").click(function() { 
     $("#custom1until").datepicker(); 
     }); 

     $("#custom2from").click(function() { 
     $("#custom2from").datepicker(); 
     }); 

     $("#custom2until").click(function() { 
     $("#custom2until").datepicker(); 
     }); 


    $("#custom3until").click(function() { 
    $("#custom3until").datepicker(); 
    }); 
    $("#custom3until").click(function() { 
    $("#custom3until").datepicker(); 
    }); 

回答

1

只要給它一個類,並選擇上。

<input type='text' class="datepick" id='custom1from'><input type='text' id='custom1until'> 
<input type='text' class="datepick" id='custom2from'><input type='text' id='custom2until'> 
<input type='text' class="datepick" id='custom3from'><input type='text' id='custom3until'> 

<input type='text' class="datepick" id='monthly1from'><input type='text' id='monthly1until'> 
<input type='text' class="datepick" id='monthly2from'><input type='text' id='monthly2until'> 
<input type='text' class="datepick" id='monthly3from'><input type='text' id='monthly3until'> 

$(".datepick").datepicker(); 
1
$('input').click(function(){ 
    $(this).datepicker(); // use "this" don't requery the DOM. 
}); 

你最好添加這些投入一類,像foo

$('input.foo').click(function(){ 
    $(this).datepicker(); 
});