2016-05-12 187 views
1

让我们考虑以下输入:jQuery Datepicker从日期设置默认值?

04/2014 

4是当月

现在我想为jQuery的日期选择器默认的日期,所以我有这样的事情:

$('.date_picker').datepicker({ 
    changeMonth: true, 
    changeYear: true, 
    showButtonPanel: true, 
    dateFormat: 'mm/yy', 
    yearRange: "-70:+10", 
    defaultDate: new Date($(this).val().slice(-4), $(this).val().substring(0, 2), 1), 
    onClose: function(dateText, inst) { 

    } 
}); 

随着前面提到的值,新日期函数返回:

Thu May 01 2014 00:00:00 GMT+0200 (CEST) 

所以问题是,为什么datepicker跳转到1946年1月?

+0

这可能会帮助:http://stackoverflow.com/questions/6646376/jquery-date-picker-default-date – DBS

+0

@DBS这是行不通的,因为是部分问题的答案是你所指的? – jycr753

+0

还有另一种方法来设置defaultDate'defaultDate:new Date('01/04/2014')'尝试使用它。 –

回答

1

该问题与您使用关键字this的上下文有关。
因此,而不是new Date($(this)...尝试使用选择器。例如:

$(function() { 
 
    $("#datepicker").datepicker({ 
 
    changeMonth: true, 
 
    changeYear: true, 
 
    showButtonPanel: true, 
 
    dateFormat: 'mm/yy', 
 
    yearRange: "-70:+10", 
 
    defaultDate: new Date($('#datepicker').val().slice(-4), $('#datepicker').val().substring(0, 2), 1), 
 
    onClose: function(dateText, inst) {} 
 
    }); 
 
    
 
    
 
    $("#datepicker-this").datepicker({ 
 
    changeMonth: true, 
 
    changeYear: true, 
 
    showButtonPanel: true, 
 
    dateFormat: 'mm/yy', 
 
    yearRange: "-70:+10", 
 
    defaultDate: new Date($(this).val().slice(-4), $(this).val().substring(0, 2), 1), 
 
    onClose: function(dateText, inst) {} 
 
    }); 
 
});
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0-rc.2/themes/smoothness/jquery-ui.css"> 
 

 
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.3/jquery.datetimepicker.min.css"> 
 

 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://code.jquery.com/ui/1.12.0-rc.2/jquery-ui.min.js"></script> 
 

 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.3/build/jquery.datetimepicker.full.min.js"></script> 
 

 

 
<p>Initialization with id selector: 
 
    <input type="text" id="datepicker" value="04/2014"> 
 
</p> 
 

 

 

 
<p>Initialization with this: 
 
    <input type="text" id="datepicker-this" value="04/2014"> 
 
</p>

+0

这没什么区别,因为这是指调用datepicker的元素,所做的是使代码重复,因为每次我使用datepicker函数而不是调用类时都会有datepicker函数。 – jycr753

+0

@ jycr753我同意你的意见。但使用选择器datepicker inicialization正常工作。答案用这两个例子更新。也许这是'datepicker'函数的一个问题 – Victor

+0

我认为是与datepicker,因为所有的控制台工作正常,我只有错误,当我尝试设置日期 – jycr753

相关问题