如何在JS自定义的HTML header组件中显示系统日期?
解决自定义HTML元素中显示系统日期的问题
你可以通过以下步骤在自定义MyHeader元素中显示系统日期:
- 修复原代码中多余的闭合
</div>标签,确保DOM结构正确,避免影响元素查找 - 在
connectedCallback渲染完innerHTML后,通过组件自身的查询方法获取date-container元素 - 生成并格式化系统日期,赋值给目标元素的文本内容
修改后的完整代码:
class MyHeader extends HTMLElement { connectedCallback(){ this.innerHTML = ` <header class="header"> <div class="logo"> <img src="C:/Users/Component 84 – 1.png" alt="Logo"> </div> <p id="admin">Admin</p> <img src="C:/Users/dhara/Desktop/ProQM/ProQM_vsCode/ic-calendar.png" id="calender"> <p id="date-container"></p> <img src="C:/Users/Asset 3@4x.png" id="protion"> </header> `; // 获取日期容器并设置系统日期 const dateContainer = this.querySelector('#date-container'); if (dateContainer) { const currentDate = new Date(); // 可选格式1:2024-05-20 // const formattedDate = `${currentDate.getFullYear()}-${String(currentDate.getMonth()+1).padStart(2, '0')}-${String(currentDate.getDate()).padStart(2, '0')}`; // 可选格式2:2024年5月20日 星期一(本地化格式) const formattedDate = currentDate.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' }); dateContainer.textContent = formattedDate; } } } customElements.define('my-header', MyHeader);
关键说明
- 使用
this.querySelector('#date-container')而非全局document.querySelector:自定义元素是独立DOM节点,组件自身的查询方法能精准定位内部元素,避免和页面其他同名ID冲突 - 日期格式可按需切换:注释中提供了两种常见格式,你可以根据需求选择或自定义格式
- DOM结构修复:原代码中多余的
</div>会导致DOM结构异常,可能影响元素查找,已移除
内容的提问来源于stack exchange,提问作者padha
相关产品推荐
相关产品推荐

