在jQuery中循环遍历图像src

时间:2016-08-17 14:38:18

标签: jquery html

我有一个包含单个字母字符串的数组。我想浏览数组中的每个字符串,并让我的网站为用户显示每个字母的相应图像几秒钟。在每个字母之间,占位符图像应显示几秒钟。

我可以让它显示每个字母,但让占位符显示。

var messageArray = ["a", "b", "c"];

function displayImages(messageArray) {
    $.each(messageArray, function(index, value) {
        $('#activeImg').attr("src", "images/letters/placeholder.png");
        console.log("PLACEHOLDER");

        setTimeout(function() { 
            $('#activeImg').attr("src", "images/letters/placeholder-letter-" + value + ".png");
            console.log(value);
        },2000 + ( index * 2000 ) );
    });
}

修改: 我相信我已经得到了我想用下面的东西。它需要添加一个新函数,用我想要显示图像的顺序创建一个新数组。

function orderImages(messageArray) {
    var imagesArray = [];
    //Create a new array with the correct images to show in order
    $.each(messageArray, function(index, value) {
        imagesArray.push("images/letters/placeholder.png");
        imagesArray.push("images/letters/placeholder-letter-" + value + ".png");
    });
    displayImages(imagesArray);
}

function displayImages(imagesArray) {
    $.each(imagesArray, function(index, value) {
        setTimeout(function() { 
            $('#activeImg').attr("src", value);
        },1000 + ( index * 1000 ) );
    });
}

2 个答案:

答案 0 :(得分:1)

您当前的功能会将messageArray设置#activeImage的来源的值预先设置为占位符图片,而不会在它们之间留出任何时间。这根本不是你想说的。在显示第一个图像之前,您基本上设置了占位符3次,因为第一个图像显示在2000毫秒之后。

这是#activeImage的时间轴:

  • 使用默认来源
  • 创建
  • 使用placeholder.png更新来源
  • 使用placeholder.png更新来源
  • 使用placeholder.png更新来源
  • 使用'a'
  • 更新来源
  • 使用'b'
  • 更新来源
  • 使用'c'
  • 更新来源

您需要做的是在显示占位符和另一个图像之间切换。

var toggleIntermission = false;
var index = 0;
function updateImage() {
    if(toggleIntermission) {
        $("#activeImage").attr("src",<placeholderpath>);
    } else {
        $("#activeImage").attr("src", <imagepath> + index);
        index = (index + 1) % messageArray
    }

    toggleIntermission != toggleIntermission;
    setTimeout("updateImage()",2000);
}

这将使您的图像循环显示字母,同时在每次更新之间放置占位符,直到结束时间或直到您关闭相应的窗口,以先到者为准。

答案 1 :(得分:0)

我相信我已经得到了我想用下面的东西。它需要添加一个新函数,用我想要显示图像的顺序创建一个新数组。

function orderImages(messageArray) {
    var imagesArray = [];
    //Create a new array with the correct images to show in order
    $.each(messageArray, function(index, value) {
        imagesArray.push("images/letters/placeholder.png");
        imagesArray.push("images/letters/placeholder-letter-" + value + ".png");
    });
    displayImages(imagesArray);
}

function displayImages(imagesArray) {
    $.each(imagesArray, function(index, value) {
        setTimeout(function() { 
            $('#activeImg').attr("src", value);
        },1000 + ( index * 1000 ) );
    });
}