如何将 jQuery UI 日期选择器初始化为查询字符串中的日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/879703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I initialize a jQuery UI datepicker to a date from the querystring?
提问by Michael Haren
Given this markup:
鉴于此标记:
// Calendar.html?date=1/2/2003
<script>
$(function() {
$('.inlinedatepicker').datepicker();
});
</script>
...
<div class="inlinedatepicker" id="calendar"/>
This will display an inline datepicker with very little effort (awesome!). How do I preset the datepicker to the date passed in via the query string?
这将显示一个内联日期选择器,只需很少的努力(太棒了!)。如何将日期选择器预设为通过查询字符串传入的日期?
Note that in this case, I don't have an input box--just a calendar attached to a div.
请注意,在这种情况下,我没有输入框——只是一个附加到 div 的日历。
回答by Ben Blank
This should work, though you may run into locale issues (specifically, M/D/Y vs. D/M/Y).
这应该有效,尽管您可能会遇到语言环境问题(特别是 M/D/Y 与 D/M/Y)。
var date = location.match(/(?:\?|&)date=(\d+\/\d+\/\d+)(&|$)/)[1];
$('.inlinedatepicker').datepicker().datepicker("setDate", new Date(date));
回答by Trond
I managed to do this with
我设法做到了这一点
$('.inlinedatepicker').datepicker().datepicker("setDate", new Date(2011,11,01)); // Date equals December 1, 2011.
I had to subtract one from the month though to get the right date as it seems that date is starting from zero (0 = January)
我不得不从月份中减去一个以获得正确的日期,因为日期似乎是从零开始的(0 = 一月)
回答by Fareed Alnamrouti
in addition to @Ben Blank answer you can use defaultDatelike this
除了@Ben Blank 答案之外,您还可以像这样使用defaultDate
var date = location.match(/(?:\?|&)date=(\d+\/\d+\/\d+)(&|$)/)[1];
$('.inlinedatepicker').datepicker({defaultDate:new Date(date)});