2013-02-08 64 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(); 
});