这是我在 StackOverflow 上的第一个问题,所以我会尽力以“正确的方式”提出这个问题。
我正在尝试使用 jQuery 动态创建 HTML 日历。基本上,我希望我的日历看起来像这样,但没有周末: http: //postimage.org/image/4xryen3ej/。
日历日期在 tbody 元素中创建:
<table>
<thead>
<tr>
<th class="weekday">Mo</th>
<th class="weekday">Tu</th>
<th class="weekday">We</th>
<th class="weekday">Th</th>
<th class="weekday">Fr</th>
</tr>
</thead>
<tbody id="dates">
</tbody>
</table>
这是jQuery代码:
var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var now = new Date;
var year = now.getFullYear();
var month = now.getMonth();
var thisMonth = now.getMonth();
var monthStart;
var monthLength;
var addDays;
var dayOfWeek;
var today;
printDate();
createCalendar();
function printDate()
{
monthStart = new Date(year, month, 1);
var monthEnd = new Date(year, month + 1);
monthLength = Math.round((monthEnd - monthStart) / (1000 * 60 * 60 * 24));
$("#dateToday").text(months[month] + " " + year + " " + monthLength);
}
function createCalendar()
{
addDays = now.getDate();
dayOfWeek = now.getDay();
today = now.getDate();
$("#dates").append("<tr>");
for (var i = 0; addDays < monthLength + 1; i++)
{
if (i < dayOfWeek)
{
$("#dates").append("<td style=\"border: 1px solid; height: 80px\">" +
"<div style=\"background-color: #EEEEEE; height: 18px; text-align: right\"></div>" +
"<div style=\"height: 62px\"></div>" +
"</td>");
}
else
{
if ((addDays == today) && (now.getMonth() == month))
{
$("#dates").append("<td style=\"border: 1px solid; height: 80px\">" +
"<div style=\"background-color: #EEEEEE; height: 18px; text-align: right\"><b>" + addDays + "</b></div>" +
"<div style=\"height: 62px\"></div>" +
"</td>");
addDays = addDays + 1;
}
else
{
if (i % 5 == 0)
{
addDays = addDays + 2;
$("#dates").append("</tr>" +
"<tr>");
}
$("#dates").append("<td style=\"border: 1px solid; height: 80px\">" +
"<div style=\"background-color: #EEEEEE; height: 18px; text-align: right\">" + addDays + "</div>" +
"<div style=\"height: 62px\"></div>" +
"</td>");
addDays = addDays + 1;
}
}
}
}
我知道网上有很多关于这类问题的例子,但我仍然无法解决问题,因此我不得不在这里发布。