欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JavaScript Basics_Fundamentals Part 2_A simple calendar

程序员文章站 2022-05-09 11:16:08
下方的日历框架是从 Active learning: A simple calendar 上整过来的。 主要任务是用 语句来让日历本显示出每月相对应的天数,相关代码已经给出,我们只需要补充 下欠缺的代码即可。 点击上方的「Reset」按钮可以重置代码,点击「Show solution」按钮可以显示答 ......
  • 下方的日历框架是从 active learning: a simple calendar 上整过来的。

  • 主要任务是用 if...else 语句来让日历本显示出每月相对应的天数,相关代码已经给出,我们只需要补充 // add conditional here 下欠缺的代码即可。

  • 点击上方的「reset」按钮可以重置代码,点击「show solution」按钮可以显示答案,然后我们点击日历上边的「select month」来选择月份,可以看到日历上对应的月份的天数发生了变化。

  • 现在对所给 solution 做些修改,判断今年是闰年还是平年,设置对应的二月份的天数。

var select = document.queryselector('select');
var list = document.queryselector('ul');
var h1 = document.queryselector('h1');

select.onchange = function() {
    var choice = select.value;
    let days = 31;
    let mydate = new date();               // 创建 date 对象
    let year = mydate.getfullyear();    // 获取当前年份
    // add conditional here
    // 闰年
    if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
        if(choice === 'february') {
            days = 29;
        }
        else if(choice === 'april' || choice === 'june' || choice === 'september'|| choice === 'november') {
            days = 30;
        }
    }
    // 平年
    else {
        if(choice == 'february') {
            days = 28;
        }
        else if(choice === 'april' || choice === 'june' || choice === 'september'|| choice === 'november') {
            days = 30;
        }
    }
  
    createcalendar(days, choice);
  }

  function createcalendar(days, choice) {
    list.innerhtml = '';
    h1.textcontent = choice;
    for(var i = 1; i <= days; i++) {
    var listitem = document.createelement('li');
    listitem.textcontent = i;
    list.appendchild(listitem);
    }
    }
   
   createcalendar(31,'january');
  • 先假定天数都为 31,经过 if 语句后,闰年二月份为 29 天,平年二月份为 28 天,四、六、九、十一月份为 30 天,则其余天数保持不变,为 31 天。

  • ===:称为等同符,当两边值的类型相同时,直接比较值;若类型不相同,直接返回 false。

  • ==:称为等值符,当等号两边的类型相同时,直接比较值是否相等;若不相同,则先转化为类型相同的值,再进行比较。