巧妙利用JS中的自定义函数——化繁为简,提高效率
利用自定义函数编写年月日时间表:
(复杂写法)如下:
<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);
}
}