1. 程式人生 > >日期的三級聯動(純js)

日期的三級聯動(純js)

<html>
<head>
    <meta charset="UTF-8">
    <title>日期三級聯動</title>
    <script>
        //網頁載入時初始化年月
        window.onload=function() {
            //初始的每月天數
            m = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
            //先給年下拉框賦內容
            for (var i =1970; i <2005; i++)
                document.form.year.options.add(new Option(i , i));
            //賦月份的下拉框
            for (var i = 1; i < 13; i++)
                document.form.month.options.add(new Option( i, i));
        }

        /**
         * 年份發生變化時進行聯動
         * @param year
         */
        function yearChange(year)
        {
            //獲得下拉列表中月份
            var month = document.form.month.options[document.form.month.selectedIndex].value;
            if (month == "0") {
                var opt = document.form.day;
                dayOptionsClear(opt);
                return;
            }
            if (month == 2 && IsPrimYear(str)) {
                m[month - 1]=29;
            }
            writeDay(m[str - 1]);
        }

        /**
         *根據月份的更改對天數列表聯動
         */
        function monthChange(month)
        {
            //獲得年份,selectedIndex當前被選擇的下標
            var Y= document.form.year.options[document.form.year.selectedIndex].value;
            if (Y== "0") {
                var opt = document.form.day;
                dayOptionsClear(opt);
            }
            if (month == 2 && IsPrimYear(Y)){
                m[month - 1]=29;
            }
            writeDay(m[month - 1]);
        }

        /**
         * 根據引數(當月的天數)新增天數的下拉列表
         * @param day_number
         */
        function writeDay(day_number) {
            var opt = document.form.day;
            dayOptionsClear(opt);
            for (var i = 1; i < (day_number + 1); i++)
                opt.options.add(new Option(i, i));
        }

        /**
         * 判斷是否為閏年
         * @param year
         * @returns {boolean}
         * @constructor
         */
        function IsPrimYear(year)
        {
            return (0 == year % 4 && (year % 100 != 0 || year % 400 == 0));
        }

        //清空天數的下拉列表
        function dayOptionsClear(opt) {
            opt.options.length = 1;
        }
    </script>
</head>
<body>
    <form name="form">
        <select name="year" onChange="yearChange(this.value)">
            <option value="0" selected>-請選擇-</option>
        </select>年
        <select name="month" onChange="monthChange(this.value)">
            <option value="0" selected>-請選擇-</option>
        </select>日
        <select name="day">
            <option value="0" selected>-請選擇-</option>
        </select>日
    </form>
</body>
</html>