在jQuery中使用回调函数的无限递归

时间:2011-02-25 04:32:36

标签: javascript jquery

尝试使用jQuery并尝试制作一个可以旋转三个图像的小型幻灯片。这是我的HTML:

<div id="slideShow">
    <img src="images/slides/slide1.jpg" width="520" height="230" />
    <img src="images/slides/slide2.jpg" width="520" height="230" />
    <img src="images/slides/slide3.jpg" width="520" height="230" />       
 </div>

这是剧本:

$(function ()
{
    var $slides = $('#slideShow img').hide(),
    slideIndex = 0;

    slideTransition = function ()
    {
        slideIndex++;
        (slideIndex == $slides.length) ? slideIndex = 0: null;
        $slides.eq(slideIndex).fadeIn(3000);
        $slides.eq(slideIndex).fadeOut(3000,slideTransition);
    }

    $slides.eq(0).fadeIn(3000);
    $slides.eq(0).fadeOut(3000, slideTransition);

});

这实际上工作正常,但我的直觉告诉我,无限递归是一件坏事。关于如何做得更好的任何建议?

2 个答案:

答案 0 :(得分:8)

你所做的不是递归。动画开始后,您的呼叫将返回。然后,计时器事件处理程序调用您的方法。你的解决方案很好。

答案 1 :(得分:0)

要删除无限递归和运行库,您可以使用jquery'“animate”函数。引用位于http://api.jquery.com/animate/