jquery幻灯片放映:让它变得更好

时间:2011-01-08 19:09:57

标签: jquery slideshow slide setinterval

我正在尝试批准我在下面使用的幻灯片,

这是html,

<!--slide-->
<div id="slide">

    <ul class="slide">
        <li><img src="contents/slide-1.jpg" alt="slide 1"/></li>
        <li><img src="contents/slide-2.jpg" alt="slide 2"/></li>
        <li><img src="contents/slide-3.jpg" alt="slide 3"/></li>
    </ul>

</div>
<!--slide-->

因为我可能有许多我想要循环它们的幻灯片集,或者我可能会不时更改id名称,所以我想在这个方法中运行函数而不是每次都更改函数中的代码对于不同的情况,

run_slide('#slide');

所以我可以使用相同的函数进行多次调用,

run_slide('#slide-2');

run_slide('#slide-3');

下面是函数,函数的第一部分运行正常,但当我想通过间隔传递id时,它的第二部分不正常 - setInterval('loop_slide('+target_slide+')',5000);

我的Firefox浏览器上有此错误消息,我不太了解它,

  

非法角色[Break On This   错误] loop_slide(#slide)

function run_slide(target_slide) {

    //add a class the the first element
    $('li:first-child',target_slide).addClass('active');

    //Set the opacity of all images to 0
    $('.slide li').css({opacity: 0.0});

    //Get the first image and display it (set it to full opacity)
    $('.slide li:first-child').css({opacity: 1.0});

    //Call the gallery function to run the slideshow, 6000 = change to next image after 6 seconds
    setInterval('loop_slide('+target_slide+')',5000);
}

function loop_slide(target_slide) {

    //var target_slide = $('#slide');

    //if no IMGs have the show class, grab the first image
    var current = ($('.slide li.active')?  $('.slide li.active') : $('.slide li:first-child'));

    //Get next image, if it reached the end of the slideshow, rotate it back to the first image
    var next = ((current.next().length) ? ((current.next().hasClass('caption'))? $('.slide li:first-child') :current.next()) : $('.slide li:first-child')); 

    //Set the fade in effect for the next image, show class has higher z-index
    current.addClass('last-active');
    next.css({opacity: 0.0})
    .addClass('active')
    .animate({opacity: 1.0}, 1000, function(){
        current.animate({opacity: 0.0}, 1000).removeClass('active last-active');

        $('.caption p',target_slide).html(caption_description);
    });

}

我该如何解决?为什么我不能将id传递给第二个函数,但我可以在第一个函数中使用?

非常感谢。

1 个答案:

答案 0 :(得分:0)

setInterval('loop_slide('+target_slide+')',5000);

似乎是问题,因为你传递的变量被解析为loop_slide(#slide)而不是loop_slide('#slide'),因此eval失败。

简单的解决方案:

setInterval('loop_slide(\''+target_slide+'\')',5000);

除此之外:如果您为了学习目的而创建此滑块,最好将其作为jquery插件编写 - 请参阅http://docs.jquery.com/Plugins/Authoring