jQuery Datepicker从日期设置默认值?
问题描述:
让我们考虑以下输入: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月?
答
该问题与您使用关键字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>
这可能会帮助:http://stackoverflow.com/questions/6646376/jquery-date-picker-default-date – DBS
@DBS这是行不通的,因为是部分问题的答案是你所指的? – jycr753
还有另一种方法来设置defaultDate'defaultDate:new Date('01/04/2014')'尝试使用它。 –