我有一个显示当前月份的chrome日历应用程序。我还有下个月和上个月的按钮,根据显示的月份来选择下个月和上个月。但是,我只希望日历到当前年份的12月和当前年份的1月为止,因此在用户点击12月/1月之后,我删除了事件处理程序。但是,当不是12月或1月时,我需要再次添加事件处理程序。我该怎么做呢?
var count = 0;
var updated = setInterval(function() {
var v = document.getElementById("CalendarMonth").innerHTML;
updatedMonth = months.indexOf(v);
}, 1000);
document.getElementById("nextMonth").addEventListener("click", nxtMonth);
function nxtMonth()
{
count = count +1;
if(nextMonth == 11)
{
console.log("the year has ended!");
document.getElementById("nextMonth").removeEventListener("click", nxtMonth);
}
else
{
nextMonth = updated + count;
//ideally, this would work. But for some reason it does not
document.getElementById("nextMonth").addEventListener("click", nxtMonth);
}
document.getElementById("previousMonth").addEventListener("click", prevMonth);
function prevMonth()
{
count = count -1;
if(previousMonth == -1)
{
console.log("the year has just started!");
document.getElementById("previousMonth").removeEventListener("click", prevMonth);
}
else if(count==-1)
{
previousMonth =1;
}
else
{
previousMonth = updated + count;
document.getElementById("previousMonth").addEventListener("click", prevMonth);
}发布于 2016-03-27 15:03:02
好吧,我认为更简单的方法是不删除点击监听器,而是在递增/递减当前月份之前立即返回。
例如,下个月的处理程序将是:
if (nextMonth == 11) {
return;
}
count++;发布于 2016-03-27 15:59:38
从可用性的角度来看,一个简单而更优雅的解决方案是添加另一个事件处理程序,分别用于“下个月”和“前几个月”按钮,以便在达到其中一个限制时停用它们。这样,浏览器将为您完成工作(它不允许用户单击它们),并且用户还将获得他们已达到限制的视觉反馈。
function checkMonth(currentMonth)
{
if(currentMonth == 12){
document.getElementById("nextMonth").disabled = true;
} else {
document.getElementById("nextMonth").disabled = false;
}
if(currentMonth == 1){
document.getElementById("previousMonth").disabled = true;
} else {
document.getElementById("previousMonth").disabled = false;
}
}只需在已有的两个按钮的事件处理程序中调用此函数。
我还没有检查过这个函数,也许你甚至可以对它进行一点优化,但这就是我想要的方法。
https://stackoverflow.com/questions/36244369
复制相似问题