如何用纯JavaScript实现下拉列表填充当前年月日,转换现有jQuery代码
纯JavaScript实现年月日下拉列表自动填充方案
基础HTML结构
下拉框ID可根据实际业务需求自行调整:
<select id="yearSelect"></select> 年 <select id="monthSelect"></select> 月 <select id="daySelect"></select> 日
完整实现代码
自带年月日联动逻辑,自动识别闰年调整2月天数,默认选中当前日期:
// 获取三个下拉框元素 const yearSelect = document.getElementById('yearSelect'); const monthSelect = document.getElementById('monthSelect'); const daySelect = document.getElementById('daySelect'); // 初始化当前日期 const now = new Date(); const currentYear = now.getFullYear(); const currentMonth = now.getMonth() + 1; const currentDay = now.getDate(); // 计算指定年月的总天数 function getDaysInMonth(year, month) { return new Date(year, month, 0).getDate(); } // 渲染年份选项,当前范围为当前年前10年到后10年,可自行修改上下限数值 function renderYear() { yearSelect.innerHTML = ''; for (let i = currentYear - 10; i <= currentYear + 10; i++) { const option = document.createElement('option'); option.value = i; option.textContent = i; if (i === currentYear) option.selected = true; yearSelect.appendChild(option); } renderMonth(); } // 渲染月份选项 function renderMonth() { monthSelect.innerHTML = ''; for (let i = 1; i <= 12; i++) { const option = document.createElement('option'); option.value = i; option.textContent = i; if (i === currentMonth) option.selected = true; monthSelect.appendChild(option); } renderDay(); } // 渲染日期选项,根据当前选中的年、月动态调整天数范围 function renderDay() { const selectedYear = Number(yearSelect.value); const selectedMonth = Number(monthSelect.value); const days = getDaysInMonth(selectedYear, selectedMonth); daySelect.innerHTML = ''; for (let i = 1; i <= days; i++) { const option = document.createElement('option'); option.value = i; option.textContent = i; if (i === currentDay && selectedMonth === currentMonth && selectedYear === currentYear) { option.selected = true; } daySelect.appendChild(option); } } // 绑定联动事件 yearSelect.addEventListener('change', renderDay); monthSelect.addEventListener('change', renderDay); // 初始化渲染 renderYear();
jQuery转原生JS核心对应逻辑
- 元素选择:jQuery的
$('#id')替换为原生document.getElementById('id'),复杂选择需求可使用document.querySelector() - 事件绑定:jQuery的
.change(回调函数)替换为原生.addEventListener('change', 回调函数) - 下拉框内容清空:jQuery的
.empty()替换为直接设置元素innerHTML = '' - 新增选项:jQuery的
.append(选项字符串)替换为原生创建option元素后调用appendChild()插入 - 取值/赋值:jQuery的
.val()替换为直接访问元素的value属性
内容的提问来源于stack exchange,提问作者elgrenka
相关产品推荐
相关产品推荐

