我有一些循环遍历n div标签的JavaScript,一次只显示一个,并且每10秒更改一次。这很有效。但我也有下一个和前一个按钮。当我点击下一个或上一个时,它们似乎正在跳过一个div。
有人可以帮忙吗?
有关更好的方法的任何建议也欢迎。我是jQuery的新手,所以我知道我还想做一些改进。感谢!!!
jQuery(document).ready(function () {
var counter = 1;
var delay = 3000; //10 seconds = 10000
var lastItem = jQuery('table[id^=featuredNo]').length - 1;
var previous = 0;
var timerID;
//argument is increment
//false is decrement
function updateCounter(increment) {
if (increment) {
counter = (counter >= lastItem) ? 0 : counter + 1;
previous = (previous >= lastItem) ? 0 : previous + 1;
} else {
counter = (counter <= 0) ? lastItem : counter - 1;
previous = (previous <= 0) ? lastItem : previous - 1;
}
}
function displayNext() {
//alert("testt" + counter);
//hide everything but current
jQuery("table[id^=featuredNo]").hide();
jQuery("#featuredNo" + counter).show();
//incrememnt the counter, so next time we show the next one
updateCounter(true);
};
//set click handlers for previous
jQuery('a[id^=featuredPrevious]').click(function () {
clearInterval(timerID);
updateCounter(false);
displayNext();
timerID = setInterval(displayNext, delay);
});
//set click handlers for next
jQuery('a[id^=featuredNext]').click(function () {
clearInterval(timerID);
updateCounter(true);
displayNext();
timerID = setInterval(displayNext, delay);
});
//start interval
timerID = setInterval(displayNext, delay);
});
答案 0 :(得分:1)
最简单的解决方案从您的下一个按钮处理程序中删除updateCounter(true),并将另一个updateCounter(false)添加到您的prev按钮处理程序:
//set click handlers for previous
jQuery('a[id^=featuredPrevious]').click(function () {
clearInterval(timerID);
updateCounter(false);
updateCounter(false);
displayNext();
timerID = setInterval(displayNext, delay);
});
//set click handlers for next
jQuery('a[id^=featuredNext]').click(function () {
clearInterval(timerID);
displayNext();
timerID = setInterval(displayNext, delay);
});