addeventlistener没有按预期工作

时间:2014-07-11 03:40:53

标签: javascript

我已将代码放在底部的codepen上,谢谢!

我写了一个javascript日历,但是当我使用addEventListener时,它会导致一些问题, 这是代码,谢谢你的帮助!

  document.addEventListener('DOMContentLoaded', function(){
var today = new Date(),
    year = today.getFullYear(),
    month = today.getMonth(),
    monthTag =["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],
    day = today.getDate();

function Calendar(selector) {
    this.el = document.getElementById(selector);
    this.draw();
}

Calendar.prototype.draw  = function() {
    var that = this,
        reset = document.getElementById('reset'),
        pre = document.getElementsByClassName('pre-button'),
        next = document.getElementsByClassName('next-button');

        pre[0].addEventListener('click', function(){that.preMonth(); });
        next[0].addEventListener('click', function(){that.nextMonth(); });
        reset.addEventListener('click', function(){that.reset(); });
    this.drawHeader();
    this.drawDays();
};

Calendar.prototype.drawHeader = function() {
    var headDay = document.getElementsByClassName('head-day'),
        headMonth = document.getElementsByClassName('head-month');

        headDay[0].innerHTML = day;
        headMonth[0].innerHTML = monthTag[month] +" - " + year;

    console.log('hello')
 };

Calendar.prototype.drawDays = function() {
    var days = document.getElementsByTagName('td'),
        startDay = new Date(year, month, 1).getDay(),
        nDays = new Date(year, month + 1, 0).getDate(),
        n = startDay;
    for(var k = 0; k <42; k++) {
        days[k].innerHTML = '';
        days[k].className = '';
    }
    for(var i  = 1; i <= nDays ; i++) {
        days[n].innerHTML = i; 
        n++;
    }
    for(var j = 0; j < 42; j++) {
        if(days[j].innerHTML === ""){
            days[j].className = "disabled";
            a = j;
        }
        if((j === day + a)&&((month===today.getMonth())&&(year===today.getFullYear()))){
            days[j].className = "today";
        }
    }
};

Calendar.prototype.preMonth = function() {
    if(month < 1){ 
        month = 11;
        year = year - 1; 
    }else{
        month = month - 1;
    }
    current = false;
    this.drawHeader();
    this.drawDays();
};

Calendar.prototype.nextMonth = function() {
    if(month >= 11){
        month = 0;
        year =  year + 1; 
    }else{
        month = month + 1;
    }
    this.draw();
}; 

 Calendar.prototype.reset = function() {
     month = today.getMonth();
     year = today.getFullYear();
     this.draw();
 }

var calendar = new Calendar('#calendar');
}, false);

正如您所看到的,preMonth()工作正常,但如果我将nextMonth()更改为{this.drawHeaders(); this.drawdays}

,则{this.draw();};工作正常

这是codepen上的代码;当你点击右键2次以上;日期显示不是预期的! http://codepen.io/puny-d/pen/eygIH

1 个答案:

答案 0 :(得分:1)

每次点击prev / next按钮都会添加新的事件处理程序。事件处理程序调用{​​{1}},它再次绑定事件处理程序。因此,在第二次点击下一个按钮后,您正在执行draw 两次

解决方案:在创建日历时,仅绑定事件处理程序一次