简体   繁体   English

用 Javascript (Html) 创建日历

[英]Creating a calendar in Javascript (Html)

I am trying to create a calendar and I have two problems.我正在尝试创建日历,但有两个问题。

  1. The months will not display as text, but rather as numbers.月份不会显示为文本,而是显示为数字。
  2. The days also won't update when I change the months.当我更改月份时,日期也不会更新。 Months have different amounts of days and thus the amount of days in the days select needs to update based on the choice in the month select.月份有不同的天数,因此天数选择中的天数需要根据月份选择中的选择进行更新。

在此处输入图片说明

Day/Month/Year format.日/月/年格式。

Here is the html code:这是html代码:

<form>
  <select id="day" name="day">
  </select>

  <select id ="month" onchange = "changeDays(this)" name="month" >
  </select>

  <select id="year" name="year">
  </select>
</form>
</div>

Here is the Javascript code:这是Javascript代码:

setCalendar('day',1, 31, false); 
setCalendar('month',1, 12, false); 
setCalendar('year',1910, 2017, false); 

function setCalendar(id, min, max, logic){

if(logic){
removeOptions(id); 
}

var monthsarray = ["January", "February","March" ,"April" ,"May" ,"June" ,"July" ,"August" ,"September", "October", "November" , "December"];  

for  (i = min; i <= max; i++){
select = document.getElementById(id); 
var opti = document.createElement("option"); 
opti.value = i; 
opti.text = id === "day" || "year" ? i.toString() : monthsarray[i-1]; 
select.add(opti); 
}

}


function changeDays(SelectObject){

switch(SelectObject){
case 1: 
//January
 setCalendar('day',1,31,true); 
break; 
case 2: 
//February
 setCalendar('day',1,28,true); 
break; 
case 3:
//March 
 setCalendar('day',1,31,true); 
break; 
case 4:
//April  
 setCalendar('day',1,30,true); 
break; 
case 5:
//May 
 setCalendar('day',1,31,true); 
break; 
case 6: 
//June
 setCalendar('day',1,30,true); 
break; 
case 7: 
//July
 setCalendar('day',1,31,true); 
break; 
case 8:  
//August
 setCalendar('day',1,31,true); 
break;
case 9: 
//September
 setCalendar('day',1,30,true); 
break; 
case 10: 
//October
 setCalendar('day',1,31,true); 
break; 
case 11: 
//November
 setCalendar('day',1,30,true); 
break; 
case 12:  
//December
 setCalendar('day',1,31,true); 
break;  
}

}

function removeOptions(selectObject)
{
    var i;
    for(i = selectObject.options.length - 1 ; i >= 0 ; i--)
    {
        selectObject.remove(i);
    }
}
opti.text = id === "day" || "year" ? i.toString() : monthsarray[i-1]; 

Year is truthy, so monthsarray will never be taken as value.年份为真,因此月数组永远不会被视为值。 Do this:做这个:

opti.text = id === "day" || id==="year" ? i.toString() : monthsarray[i-1]; 

Also you dont want你也不想

switch(SelectObject){

You want to switch on its value:你想打开它的值:

switch(SelectObject.options[SelectObject.selectedIndex].value){

Mistake three误区三

select.add(opi) => select.appendChild(opi)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM