点击按钮切换周历功能实现及现有代码解析求助
Hey there! Let's first unpack what your existing code does, then we'll fix the nextWeek() function to make your calendar switch to the next week properly.
What Your Current Code Does
Let's break down the initial code line by line:
let d = new Date();grabs today's date.let t = d.getDay();gets the current day of the week (0 = Sunday, 6 = Saturday).- It selects all elements with the
weekdayclass (the date spans in your table headers). - The loop fills in each day's date:
- If
t > i(e.g., today is Wednesday (t=3) and we're filling Sunday (i=0)), it calculates the date by subtracting days from today. - If
t < i(e.g., filling Thursday (i=4) when today is Wednesday), it adds days starting from 1. - When
t === i, it highlights the current day's parent element and shows today's date.
- If
The problem here is that the code only calculates dates relative to today, and there's no way to track what week we're currently viewing—so when you click the next week button, we have no reference point to calculate the next week's dates. Also, the current date math doesn't handle cross-month/year cases (e.g., if today is January 31, adding a day should take you to February 1, not January 32).
Updated Code with Next Week Functionality
Let's rewrite this to fix those issues. We'll add a variable to track the start of the current week, then create a reusable function to render the week based on that start date.
Full HTML (no changes needed here, just keeping it for context)
<div id="wrapper"> <div id="est-finish-dates"> <table> <tr> <th>Sunday<br/>(<span class="weekday"></span>)</th> <th>Monday<br/>(<span class="weekday"></span>)</th> <th>Tuesday<br/>(<span class="weekday"></span>)</th> <th>Wednesday<br/>(<span class="weekday"></span>)</th> <th>Thursday<br/>(<span class="weekday"></span>)</th> <th>Friday<br/>(<span class="weekday"></span>)</th> <th>Saturday<br/>(<span class="weekday"></span>)</th> </tr> </table> </div> </div> <button onclick="nextWeek()">next week</button>
Updated JavaScript
// Track the start of the current week (Sunday of the current week) let currentWeekStart = new Date(); // Adjust to the Sunday of this week: subtract the current day of the week (0=Sunday, so no change if today is Sunday) currentWeekStart.setDate(currentWeekStart.getDate() - currentWeekStart.getDay()); // Reusable function to render the week based on a given start date function renderWeek(startDate) { const weekdayElements = document.querySelectorAll(".weekday"); // Reset all background colors first weekdayElements.forEach(el => { el.parentNode.style.backgroundColor = ""; }); // Loop through each day of the week (0=Sunday to 6=Saturday) weekdayElements.forEach((el, index) => { // Create a date for the current day in the week const dayDate = new Date(startDate); dayDate.setDate(startDate.getDate() + index); // Format the date as MM/DD/YYYY const formattedDate = `${dayDate.getMonth() + 1}/${dayDate.getDate()}/${dayDate.getFullYear()}`; el.innerHTML = formattedDate; // Highlight today if it's in this week const today = new Date(); if (isSameDay(dayDate, today)) { el.parentNode.style.backgroundColor = "rgb(100, 100, 100)"; } }); } // Helper function to check if two dates are the same day (ignoring time) function isSameDay(date1, date2) { return date1.getFullYear() === date2.getFullYear() && date1.getMonth() === date2.getMonth() && date1.getDate() === date2.getDate(); } // Next week function: add 7 days to the current week start and re-render function nextWeek() { currentWeekStart.setDate(currentWeekStart.getDate() + 7); renderWeek(currentWeekStart); } // Render the initial week when the page loads renderWeek(currentWeekStart);
Key Improvements Explained
currentWeekStartvariable: This tracks the Sunday of the week we're currently viewing. We initialize it by adjusting today's date to the nearest previous Sunday.renderWeek()function: This reusable function takes a start date (Sunday) and calculates each day of the week from there. Usingnew Date(startDate)ensures we don't modify the original start date, andsetDate()automatically handles cross-month/year transitions (e.g., January 31 + 1 day becomes February 1).isSameDay()helper: Checks if a displayed date is today, so we can highlight it correctly even when viewing future weeks.nextWeek()function: Simply adds 7 days tocurrentWeekStartand callsrenderWeek()to update the calendar.
Now when you click the "next week" button, the calendar will correctly show the dates for the following week, including handling month/year changes!
内容的提问来源于stack exchange,提问作者Shing Ysc

