下一个和上一个按钮不起作用

时间:2014-11-24 20:59:03

标签: javascript button

此代码用于制作日历。当我点击下一个按钮时没有任何反应。我希望当我点击下一个按钮时,页面将加载第二个月,而前一个按钮也是如此。

var month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var days =  [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var body = document.body;
var counter = 0;

function calendar(){
  for(var i = 1; i<=days[counter]; i++){
    var div = document.createElement("div");
    var calendar1 = document.createTextNode(i);
    div.appendChild(calendar1);
    body.appendChild(div);
  } 
}

function next(){
  counter++;
}

function previous(){
  counter--;
}
calendar(0);
*{
  padding:0;
  border:0;
}
div{
  float:left;
  border: 1px solid black;
  height:100px;
  width:100px;
}
<button onclick="next()">Next</button>
<button onclick="previous()">Previous</button>

1 个答案:

答案 0 :(得分:0)

似乎您想在更新counter后重新绘制日历。

然后,您的nextprevious函数应调用calendar

但请注意calendar应在显示更新的日历之前清除当前日历。

var month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
    days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
    wraper = document.getElementById('calendar'),
    counter = 0;
function calendar(){
  wraper.innerHTML = ''; // Clear current calendar
  for(var i = 1; i<=days[counter]; i++){
    var div = document.createElement("div");
    var calendar1 = document.createTextNode(i);
    div.appendChild(calendar1);
    wraper.appendChild(div);
  } 
}
document.getElementById('next').onclick = function next(){
  ++counter;
  calendar()
};
document.getElementById('prev').onclick = function previous(){
  --counter;
  calendar()
};
calendar();
*{
  padding:0;
  border:0;
}
#calendar > div{
  float:left;
  border: 1px solid black;
  height:100px;
  width:100px;
}
<button id="next">Next</button>
<button id="prev">Previous</button>
<div id="calendar"></div>