信息发布→ 登录 注册 退出

基于JavaScript实现年月日三级联动

发布时间:2026-01-11

点击量:

本文实例为大家分享了JavaScript实现年月日三级联动的具体代码,供大家参考,具体内容如下

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>年月日三级联动</title>
</head>
<body onload="initYear(),initMonth()">
<select id="year"></select>年
<select id="month" onchange="initDate()"></select>月
<select id="date"></select>日
<script>
    /**
     * 初始化年
     */
    function initYear() {
        //获得当前年份
        let curYear = new Date().getFullYear();
        //获得年列表对象
        let yearObj = document.getElementById("year");
        yearObj.options.add(new Option("---请选择年---", ""));
        for (let year = curYear; year > curYear - 100; year--) {
            let option = new Option(year, year);
            yearObj.options.add(option);
        }
    }

    /**
     * 初始化月份
     */
    function initMonth() {
        //获得年列表对象
        let monthObj = document.getElementById("month");
        monthObj.options.add(new Option("---请选择月份---", ""));
        for (let month = 1; month <= 12; month++) {
            let option = new Option(month, month);
            monthObj.options.add(option);
        }
    }

    /**
     * 初始化日
     */
    function initDate() {
        let dateObj = document.getElementById("date");
        //获得当月选中月份
        let month = document.getElementById("month").value;
        //当月份选择完毕,再弹出对应日期
        dateObj.options.add(new Option("---请选择日期---", ""));
        //将month转化成数字
        month = parseInt(month);
        //定义每月的天数
        let days = 31;
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                days = 30;
                break;
            case 2:
                //需要判断是否为闰年,获得当前选中的年
                let year = document.getElementById("year").value;
                if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
                    days = 29;
                } else {
                    days = 28;
                }
                break;
        }
        //将得到的天数,循环输出
        for (let i = 1; i <= days; i++) {
            let option = new Option(i, i);
            dateObj.options.add(option);
        }
    }
</script>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

标签:# UTF  # onload  # year  # month  # select  # id  # title  # meta  # head  # en  # lang  # charset  # js年月日三级联动  # 判断是否  # 转化成  # 大家多多  # 具体内容  # 大家分享  # 当月  # 弹出  # 请选择  # js实现年月日表单三级联动  # js三级联动  # js年月日联动  
在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!