如何先为日历今日<td>添加<p>标签再追加文本节点?
解决方案
你只需要调整原有代码的节点创建和追加顺序,先创建<p>元素,再将文本节点放入<p>,最后把<p>添加到目标<td>中。
修改后的核心代码片段
const td1 = document.getElementById('todaycell'); // 创建新的p标签元素 const pElement = document.createElement('p'); // 创建文本节点 const text = document.createTextNode("Total Units = "); // 将文本节点追加到p标签内 pElement.appendChild(text); // 将p标签追加到td元素内 td1.appendChild(pElement);
完整修改后的JavaScript代码
let CURR_DATE = new Date(); const MONTHS = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; function getTotalDaysInMonth(year, month) { return 32 - new Date(year, month, 32) .getDate(); } const grid = document.querySelectorAll('#calendar-table td'); const dateText = document.getElementById('date-text'); const calendarTitle = document.querySelectorAll('#calendar-title')[0]; // clears all cells function clearGrid() { grid.forEach(cell => { cell.innerHTML = ''; cell.removeAttribute("id", 'todaycell'); }); } function renderCalendar(date = CURR_DATE) { clearGrid(); // sets month and year calendarTitle.innerText = `${MONTHS[date.getMonth()]}, ${date.getFullYear()}`; const dayOfWeek = date.getDay(); const dateOfMnth = date.getDate(); let totalMonthDays = getTotalDaysInMonth( date.getFullYear(), date.getMonth() ); let startDay = dayOfWeek - dateOfMnth % 7 + 1; if (startDay < 0) startDay = (startDay + 45) % 7; for ( let i = startDay; i < totalMonthDays + startDay; i++ ) grid[i % 45].innerHTML = (i - startDay + 1); let today = new Date() if (today.toDateString() === date.toDateString()) { grid[(startDay + dateOfMnth - 1) % 45].setAttribute("id", 'todaycell') const td1 = document.getElementById('todaycell'); // 创建新的p标签元素 const pElement = document.createElement('p'); // 创建文本节点 const text = document.createTextNode("Total Units = "); // 将文本节点追加到p标签内 pElement.appendChild(text); // 将p标签追加到td元素内 td1.appendChild(pElement); }; dateText.innerHTML = today.toLocaleDateString("en-US", { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }); } [...document.getElementsByClassName('button')].forEach(button => { let incr = 1; // left button decreases month if (button.classList.contains('buttonPrevious')) incr = -1; button.onclick = function() { CURR_DATE.setMonth(CURR_DATE.getMonth() + incr); renderCalendar(); }; let today = new Date() const tdate = document.querySelector("#date-text"); tdate.onclick = function () { CURR_DATE = new Date(); renderCalendar(today); }; }) //clearGrid() renderCalendar();
关键步骤说明
- 使用
document.createElement('p')创建一个全新的<p>DOM元素 - 保持原有创建文本节点的逻辑不变
- 先将文本节点挂载到
<p>元素上,再把<p>元素挂载到目标<td>中,实现嵌套结构
内容的提问来源于stack exchange,提问作者Jon Beckner
相关产品推荐
相关产品推荐

