利用自定義函數編寫年月日時間表: (複雜寫法)如下: <body> <select id="year" size="1" style="width: 70px;"></select> <select id="month" size="1" style="width: 50px;"></select> ...
利用自定義函數編寫年月日時間表:
(複雜寫法)如下:
<body>
<select id="year" size="1" style="width: 70px;"></select>
<select id="month" size="1" style="width: 50px;"></select>
<select id="day" size="1" style="width: 50px;"></select>
</body>
<script>
//年月日選擇表
var time =new Date();
var year_now = time.getFullYear();
//選取元素
var slt_year = document.getElementById('year');
var slt_month = document.getElementById('month');
var slt_day = document.getElementById('day');
//利用迴圈確定年份範圍
for(i=1990;i<=year_now;i++){
var opt1 = document.createElement('option');
opt1.innerText = i;
slt_year.appendChild(opt1);
}
//利用迴圈確定月份範圍
for(i=1;i<13;i++){
var opt2 = document.createElement('option');
opt2.innerText = i;
slt_month.appendChild(opt2);
}
//自定義改變事件函數
slt_year.onchange = function(){
change();
}
slt_month.onchange = function(){
change();
}
//自定義函數
function change(){
var year = slt_year.selectedOptions[0].innerText;
var month = slt_month.selectedOptions[0].innerText;
if(month ==4 || month ==6 || month ==9 || month ==11){
slt_day.innerText = "";
for(i=1;i<31;i++){
var new_opt3 = document.createElement('option');
new_opt3.innerText = i;
slt_day.appendChild(new_opt3);
}
}else if(month==2){
if(year%4==0 && year%100 !=0 || year%400==0){
slt_day.innerText = "";
for(i=1;i<30;i++){
var new_opt3 = document.createElement('option');
new_opt3.innerText = i;
slt_day.appendChild(new_opt3);
}
}
else{
slt_day.innerText = "";
for(i=1;i<29;i++){
var new_opt3 = document.createElement('option');
new_opt3.innerText = i;
slt_day.appendChild(new_opt3);
}
}
}else{
slt_day.innerText = "";
for(i=1;i<32;i++){
var new_opt3 = document.createElement('option');
new_opt3.innerText = i;
slt_day.appendChild(new_opt3);
}
}
}
(簡寫寫法)如下:
//自定義改變事件函數
slt_year.onchange = function(){
change();
}
slt_month.onchange = function(){
change();
}
//自定義函數
function change(){
var year = slt_year.selectedOptions[0].innerText;
var month = slt_month.selectedOptions[0].innerText;
if(month ==4 || month ==6 || month ==9 || month ==11){
add_day(30);
}else if(month==2){
if(year%4==0 && year%100 !=0 || year%400==0){
add_day(29);
}else{
add_day(28);
}
}else{
add_day(31);
}
}
//自定義通用函數
function add_day(i_max){
slt_day.innerText = "";
for(i=1;i<=i_max;i++){
var new_opt3 = document.createElement('option');
new_opt3.innerText = i;
slt_day.appendChild(new_opt3);
}
}