Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/378.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery重复数组循环以更改标记属性_Javascript_Jquery_Jquery Plugins_Slider - Fatal编程技术网

Javascript jQuery重复数组循环以更改标记属性

Javascript jQuery重复数组循环以更改标记属性,javascript,jquery,jquery-plugins,slider,Javascript,Jquery,Jquery Plugins,Slider,我正在制作一个简单的滑块,通过更改img标记的src属性和锚定标记的属性来工作。这就是我到目前为止的想法: (function($){ var slides = [ 'http://placehold.it/801x350', 'http://placehold.it/802x350', 'http://placehold.it/803x350' ], titles = [ 'Title 1',

我正在制作一个简单的滑块,通过更改
img
标记的
src
属性和锚定标记的属性来工作。这就是我到目前为止的想法:

(function($){
    var slides = [
        'http://placehold.it/801x350',
        'http://placehold.it/802x350',
        'http://placehold.it/803x350'
    ],
    titles = [
        'Title 1',
        'Title 2',
        'Title 3'
    ],
    links =  [
        'http://test1.com',
        'http://test2.com',
        'http://test3.com'
    ],
    image = $('#stretch-img'),
    anchor = $('.featured-title>h2>a');

    var interval = setInterval(function() {
        image.attr('src', slides[0]);
        anchor.attr('href', links[0]);
        anchor.html(titles[0]);
    }, 3000);
})(jQuery);
我希望间隔以简单的淡入淡出效果连续循环通过阵列。什么是做这件事的最好方法,或者任何方法,真的,因为我没有

谢谢


非常感谢您的帮助。

要在阵列中循环,您可以设置当前位置变量和保存阵列长度的变量:

var current = 0,
    length  = slides.length,
    interval = setInterval(function() {
        image.attr('src', slides[current]);
        anchor.attr('href', links[current]).html(titles[current]);

        current++;
        if (current >= length) {
            current = 0;
        }
    }, 3000);
然后要淡出,您可以淡出,更改源,然后淡入:

        image.fadeOut(500, function () {
            image.attr('src', slides[current]).fadeIn(500);
            anchor.attr('href', links[current]).html(titles[current]);

            current++;
            if (current >= length) {
                current = 0;
            }
        });
fadeIn(500)
启动时,这可能导致图像未完全加载,这可以通过使用连接到
image
元素的
load
事件的事件处理程序来修复:

var image = $('#stretch-img').on('load', function () {
    image.fadeIn(500);
});
然后,您可以从间隔功能中删除
fadeIn(500)
,因为它将在加载图像时触发。每当图像源更改且新源完成加载时,
load
事件将触发


请注意,
.on()
在jQuery 1.7中是新的,在本例中与
.bind()
相同。

。那很好用。非常感谢你。我真的很感激。但有一个问题:我使用了淡入淡出的代码。有个问题。幻灯片和标题相差一页。i、 图1的标题是2。我通过在fadoOut回调中放置锚修改代码来修复它。我为什么要这么做?当前的++在这两条语句之后。我真的很想了解这一点。再次感谢。@Aayush发生这种情况是因为
current
变量在
fadeOut
回调函数之前递增。我更新了答案,以增加
淡出
回调函数中的
当前
变量。