简体   繁体   English

jQuery Click事件仅触发一次

[英]Jquery Click Events Fires Only Once

Can you please take a look at this Demo and let me know why the click events on #pre and #nex only firing once! 您能否看一下这个演示 ,让我知道为什么#pre#nex上的点击事件仅触发一次!

var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

var d = new Date();
var n = d.getMonth();
$("#month").html(months[n]);

$(".row").on('click' , '#pre',  function(){
    $("#month").html(months[n-1]);
});

$("#nex").on('click' , function(){
  $("#month").html(months[n+1]);
});

I also tried to use the delegate method on #pre which again didn't work 我也尝试在#pre上使用委托方法,这再次不起作用

You need to decrement and increment the value of n for this to work. 您需要减小和增大n的值才能使其工作。 You also need to make sure that you are not outside the bounds of the array when you do so, otherwise you will get an index out of range exception. 您还需要确保这样做时,您不在数组的边界之外,否则您将获得索引超出范围的异常。

$(".row").on('click' , '#pre',  function(){
    n = (n === 0) ? months.length - 1 : n - 1;
    $("#month").html(months[n]);
});

$("#nex").on('click' , function(){
    n = (n === months.length - 1) ? 0 : n + 1;
    $("#month").html(months[n]);
});

You aren't changing the value of n, so you're always going to get last month from today. 您没有更改n的值,所以您总是要从今天开始获取上个月。 Get the current value of #month first in your onclick method. 首先在您的onclick方法中获取#month的当前值。

Your events are firing - you are just setting the same value each time they fire. 您的事件正在触发-您每次触发时都设置相同的值。 try adding n+=1 and n-=1 in your events to change the value. 尝试在事件中添加n + = 1和n- = 1来更改值。

i am edit your code and now working you should change counter value will each click .. 我正在编辑您的代码,现在可以更改计数器的值了,每次点击..

var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var months = [“一月”,“二月”,“三月”,“四月”,“五月”,“六月”,“七月”,“八月”,“九月”,“十月”,“十一月”,“十二月“]; var days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; var days = [“星期一”,“星期二”,“星期三”,“星期四”,“星期五”,“星期六”,“星期日”]; var d = new Date(); var d = new Date(); var n = d.getMonth(); var n = d.getMonth();

$("#month").html(months[n]);

$(".row").on('click' , '#pre',  function(){
    $("#month").html(months[n-1]);
    n=n-1
});

$("#nex").on('click' , function(){
  $("#month").html(months[n+1]);
    n=n+1
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM