導讀js簡單的年月聯(lián)動實現(xiàn)代碼_時間日期:HTML 代碼如下: 源碼: 代碼如下: function vYearMonth(yearObjId, monthObjId) { var selYear = document.getElementById(yearObjId); var selMonth = document.getElementById(monthObjId);
HTML 代碼如下:
源碼: 代碼如下: function vYearMonth(yearObjId, monthObjId) { var selYear = document.getElementById(yearObjId); var selMonth = document.getElementById(monthObjId); var myDate = new Date(); //當前日期 var myYear = myDate.getFullYear(); //當前年 var myMonth = myDate.getMonth() + 1; //當前月 var yearMin = -2; //年份范圍值,也當前年比較的差值 var yearMax = 10; //年份范圍值,也當前年比較的差值
//Begin年******************************* selYear.options.add(new Option("", "")); for (var i = yearMin; i < yearMax; i++) { var opt = new Option(myYear + i, myYear + i); selYear.options.add(opt); } //這里1-yearMin表示選中當前年,用1是因為開頭有插入"" selYear.options.selectedIndex = 1 - yearMin; //End年*******************************
//Begin月******************************* selMonth.options.add(new Option("", "")); for (var i = 0; i < 12; i++) { var opt = new Option(i + 1, i + 1); selMonth.options.add(opt); } //選中當前月 selMonth.options.selectedIndex = myMonth; //End月*******************************
selYear.onchange = function () { if (this.value == "") { selMonth.selectedIndex = 0; } else { if (selMonth.value == "") { selMonth.selectedIndex = myMonth; } } }; }