【问题标题】:Script not working for second instance of referenced component脚本不适用于引用组件的第二个实例
【发布时间】:2012-09-28 22:22:12
【问题描述】:

我有一个脚本用来旋转无序列表 (LI) 中的图像。如果页面上只有一个引用类的实例,则脚本可以正常工作。但是,如果我有 2 个旋转组件实例,则第二个实例不会响应。

认为解决方案是让脚本继续运行,直到第二个旋转器得到它,但我不确定。我尝试了几次修改,但没有成功。当前脚本如下:

function theRotator() {
    //Set the opacity of all images to 0
    $('div.rotator ul li').css({opacity: 0.0});

    // Remove images that only show in main-content
    $('div.rotator ul li.page-only').remove();

    //Get the first image and display it (gets set to full opacity)
    $('div.rotator ul li:first').css({opacity: 1.0});

    //Call the rotator function to run the slideshow, 6000 = change to next image after 6 seconds
    setInterval('rotate()',4000);
}

function rotate() { 
    //Get the first image
    var current = ($('div.rotator ul li.show')?  $('div.rotator ul li.show') : $('div.rotator ul li:first'));

    if ( current.length == 0 ) current = $('div.rotator ul li:first');

    //Get next image, when it reaches the end, rotate it back to the first image
    var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div.rotator ul li:first') :current.next()) : $('div.rotator ul li:first'));

    //Un-comment the 3 lines below to get the images in random order

    //var sibs = current.siblings();
    //var rndNum = Math.floor(Math.random() * sibs.length );
    //var next = $( sibs[ rndNum ] );


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

    //Hide the current image
    current.animate({opacity: 0.0}, 1000)
    .removeClass('show');

};
setTimeout(function(){
    $(document).ready(function() {      
        //Load the slideshow
        theRotator();
        $('div.rotator').fadeIn(500);
        $('div.rotator ul li').fadeIn(500); // tweek for IE
    });
}, 500);

【问题讨论】:

    标签: javascript jquery instance repeat


    【解决方案1】:

    您可能需要将选择器中的:first 替换为:first-child:first 的行为类似于 .first() 并且只选择一个元素,而 :first-child 的行为类似于其 CSS 等效项。

    【讨论】:

    • 好建议。然而,这种改变似乎并没有做任何事情。我认为“:”首先消除了 .first() 的行为。
    • 您能否在jsfiddle.net 提供您的代码的功能示例,以便我们看看它在做什么?
    • 我用:first-child 替换了:first 的所有实例,它似乎工作正常。 jsfiddle.net/mblase75/xjuah -- 另请注意,我更改了您的 setInterval 呼叫以正常工作。
    • 非常感谢!我刚刚注意到另一个相关问题。如果第二个旋转器的 LI 比第一个旋转器多,则第一个旋转器停止,直到第二个旋转器完成其旋转。请参阅我的更新示例,您的更改在这里实现:jsfiddle.net/trobbins26/5U4Cr/17
    • 这可能需要重新考虑您的程序流程。考虑为每个旋转器使用单独的setInterval。如果您仍然遇到问题,请尝试尽可能简化您的代码并发布一个单独的问题。
    猜你喜欢
    • 2012-11-14
    • 2019-04-28
    • 2021-08-26
    • 1970-01-01
    • 2019-01-25
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    相关资源
    最近更新 更多