用Javascript(Html)创建日历

时间:2017-02-13 15:54:50

标签: javascript html

我正在尝试创建日历,但我有两个问题。

  1. 月份不会显示为文字,而是显示为数字。
  2. 当我更改月份时,日期也不会更新。月份具有不同的天数,因此根据月份选择中的选择需要更新天数。
  3. enter image description here

    日/月/年格式。

    这是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>
    

    以下是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);
        }
    }
    

1 个答案:

答案 0 :(得分:1)

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

年度是真实的,因此数月不会被视为价值。这样做:

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

你也不想要

switch(SelectObject){

您想要启用其值:

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

错误三

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