gpt4 book ai didi

javascript - 为什么 jQuery 单击(下一步)按钮无法正常工作?

转载 作者:行者123 更新时间:2023-11-28 20:49:29 24 4
gpt4 key购买 nike

我想用简单的分页制作简单的 jQuery 淡入淡出轮播。
一切都运转良好。但是,当我单击“下一步”按钮时,轮播每次都会返回到第一项。

如何解决这个问题?

The Fiddle

如果 fiddle 变得陈旧,请参阅我的 HTML:

<body>    
<ul id="carousel">
<li class="is-showing" ><img src="http://aarontennyson.com/tutorials/demos/slide_show_fade/images/slide1.jpg" width="960" height="375" alt="image 1" /></li>
<li class="is-showing" ><img src="http://aarontennyson.com/tutorials/demos/slide_show_fade/images/slide2.jpg" width="960" height="375" alt="image 2" /><li>
<li class="is-showing" ><img src="http://aarontennyson.com/tutorials/demos/slide_show_fade/images/slide3.jpg" width="960" height="375" alt="image 3" /></li>
<li class="is-showing" ><img src="http://aarontennyson.com/tutorials/demos/slide_show_fade/images/slide4.jpg" width="960" height="375" alt="image 4" /></li>
<li class="is-showing" ><img src="http://aarontennyson.com/tutorials/demos/slide_show_fade/images/slide5.jpg" width="960" height="375" alt="image 5" /></li>
</ul>
<span class="prev">prev</span>
<span class="next">next</span>
</body>

和脚本:

$(document).ready(function() {
slideShow();
});

function slideShow() {
var showing = $('#carousel .is-showing');
var next = showing.next().length ? showing.next() : showing.parent().children(':first');

showing.fadeOut(800, function() {
next.fadeIn(800).addClass('is-showing');
}).removeClass('is-showing');
setTimeout(slideShow, 5000);

$(".next").click(function() {
showing.fadeOut(800, function() {
next.fadeIn(800).addClass('is-showing');
}).removeClass('is-showing');
})
}​

最佳答案

您需要重写一些代码才能解决这个问题。拆分函数中的重复操作。

Fixed example

新脚本:

$(document).ready(function() {
slideShow();
});

function slideShow() {
var slides = $('#carousel li');
var previousIndex = 0,
currentIndex = 0,
timer;
slides.hide().removeClass('is-showing').eq(currentIndex).show().addClass('is-showing');

function nextSlide() {
previousIndex = currentIndex;
if (currentIndex < slides.length - 1) currentIndex++;
else currentIndex = 0;
switchSlides();
}

function switchSlides() {
slides.eq(previousIndex).removeClass('is-showing').fadeOut(300, function() {
slides.eq(currentIndex).addClass('is-showing').fadeIn(300);
autoRotate();
});
}

function autoRotate() {
clearTimeout(timer);
timer = setTimeout(nextSlide, 5000);
}

autoRotate();
$(".next").click(nextSlide);
}​

关于javascript - 为什么 jQuery 单击(下一步)按钮无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12769660/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com