JQuery UI datepicker神奇地停止了正确的月份

时间:2012-08-01 20:11:37

标签: jquery-ui jquery-ui-datepicker

编辑:我刚刚在这里演示了一个问题:http://jsfiddle.net/GvjRd/3/

我有一个使用JQuery UI datepicker的Web工具。它已经工作了好几个星期,但突然间它今天停止了工作。无论我在日历上选择什么日/月/年,当我选择一天并致电alert(currentTime.getMonth());时,它会返回'7'。它返回日/年就好了。

我开始自己测试日期选择器,制作一个非常简单的页面:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <link type="text/css" href="ui-lightness/jquery-ui-1.8.21.custom.css" rel="stylesheet" />
    <link rel="stylesheet" href="demos.css">
    <script type="text/javascript" src="jquery-1.7.2.min.js"></script>
    <script type="text/javascript" src="jquery-ui-1.8.21.custom.min.js"></script>
    <script type="text/javascript">
        $(function() {
            $("#datepicker").datepicker({
                onSelect : function(dateText, inst) {
                    var currentTime = new Date();
                    currentTime.setDate($("#datepicker").datepicker("getDate").getDate());
                    alert(currentTime.getMonth());
                }
            });
        });
    </script>

</head>
<body>
            Date:
            <input type="text" id="datepicker">
</body>

即使在这个页面上,无论我选择什么日/月/年组合,警报都会显示'7'。其他人有这个问题吗?

2 个答案:

答案 0 :(得分:0)

JavaScript中的月份为零,因此7 =第8个月或8月。

在您的示例中,您将currentTime设置为今天,然后仅将该日期对象的日期更改为日历上选择的日期,并保持月份和年份不变。因此,currentTime.getMonth()将始终显示运行脚本的月份,而不是从日历中选择的日期。为此,请使用currentTime.setMonth($("#datepicker").datepicker("getDate").getMonth());

<强> jsFiddle example

答案 1 :(得分:0)

请确保您未提前设置currentTime变量:

$(function() {
                $("#datepicker").datepicker({
                    onSelect : function(dateText, inst) {
                        var currentTime;
                        currentTime = $("#datepicker").datepicker("getDate");
                        alert(currentTime.getMonth() + 1);
                    }
                });
            });​