您的位置:首页 > 编程学习 > > 正文

js三级联动列表(基于JavaScript实现年月日三级联动)

更多 时间:2021-10-27 10:02:51 类别:编程学习 浏览量:1822

js三级联动列表

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

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

js三级联动列表(基于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>
    
  • 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持开心学习网。

    标签:js 三级联动