JavaScript日历奇怪的行为

时间:2012-08-04 14:23:47

标签: javascript

我看到还有其他的JS日历,但我想尝试一下,看看我是否可以自己做。我遇到了一些障碍。似乎当我运行我的脚本来生成这个月的(八月)日历时,我得到的是29天而不是31天。任何人都可以看到我做错了什么并指出我正确的方向吗?

var arrMonth = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec");
var arrWeek = new Array("Su", "M", "Tu", "W", "Th", "F", "Sa");

var now = new Date();
var thisYear = now.getFullYear();
var thisMonth = now.getMonth();
var thisDate = now.getDate();
var thisDay = now.getDay();



var firstMonth = new Date();
var tempYear = firstMonth.setYear(thisYear);
var tempMonth = firstMonth.setMonth(thisMonth);
var tempDate = firstMonth.setDate(1);

var firstDay = firstMonth.getDay();
var totalDays = numberOfDays(thisYear, thisMonth);

var dayCounter = 1;
var strHTML = "";

strHTML += "<table border='1'>";
strHTML += "<tr>";
for(var x=0; x<arrMonth.length; x++){
    if(x == thisMonth){
        strHTML += "<td colspan='7' align='center'>" + arrMonth[x] + "</td>";
    }
}
strHTML += "</tr>";

strHTML += "<tr>";
for(var x=0; x<arrWeek.length; x++){
    strHTML += "<td align='center'>" + arrWeek[x] + "</td>";    
}
strHTML += "</tr>";

strHTML += "<tr>";
for(var x=0; x<40; x++){
    if(x < firstDay){
        strHTML += "<td>&nbsp;</td>";
    }
    else if(x == firstDay){
        strHTML += "<td align='center'>" + dayCounter + "</td>";
        dayCounter++;
    }
    else{
        if(x <= totalDays){
            if((x % 7) == 0){
                strHTML += "</tr>";
                strHTML += "<tr>";
                strHTML += "<td align='center'>" + dayCounter + "</td>";
            }
            else{
                strHTML += "<td align='center'>" + dayCounter + "</td>";
            }
            dayCounter++;
        }
    }
}
alert(dayCounter + " : " + totalDays);
strHTML += "</tr>";
strHTML += "</table>";

alert(strHTML);

function numberOfDays(year, month) { 
    var d = new Date(year, month, 0); 
    return d.getDate(); 
} 

1 个答案:

答案 0 :(得分:0)

您使用x作为日历中单元格数量的计数器,但将其与该月份的天数进行比较。也就是说,改变这一行:

if(x <= totalDays){

进入这个:

if( x < totalDays + firstDay ) {

演示:http://jsfiddle.net/j9rtm/