【问题标题】:Changing img src from a populated array从填充数组更改 img src
【发布时间】:2014-09-27 18:58:16
【问题描述】:

我创建了一个脚本来填充一个包含 0-118 数字的数组,并使用一个函数对其进行随机播放。

例如:

var Arr = new Array ();

for (var i = 0; i < 119; i++) {
    Arr[i] = i;
}

function shuffle(o){ 
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

newArray = shuffle(Arr);

我有一个包含 24 个拇指的画廊,分别命名为 0.jpg、1.jpg 等 118.jpg。我需要从数组中为每个拇指调用一个数字。

php 中的等价物是:

<?php $arr = array_rand(range(1, 117), 24);?>
<img src="images/<?php echo $arr[0].'.jpg'; ?>" />

这可以在 Javascript 中完成吗?我应该如何处理它?用拇指的名字创建一个数组是不切实际的。

【问题讨论】:

标签: javascript arrays gallery shuffle


【解决方案1】:

你可以给图像一个类然后做

$(".imageClass").each(function(i) {
 this.src="/images/"+newArray[i]+".jpg";
});

【讨论】:

  • 这个脚本会在将 attr 添加到类之前对数组进行洗牌吗?这样做,可能是重复的?
  • 我不太明白你的意见。我也没有看洗牌。这是另一种选择:stackoverflow.com/questions/2450954/…
【解决方案2】:

我设法做到了(来自同事的帮助):

var array           = [];   // create array for the images

for (var i = 0; i < 90; i++) {
    array[i] = i;
}

var new_array       = shuffle(array);   // shuffled array

for (var i = 1; i <= 24 ; i++) {
    $('#' + i).attr('src', 'images/banner/' + new_array[i-1] + '.jpg');
}

window.setInterval(function(){
    var random_position = Math.floor(Math.random() * 24) + 1;   // grab a random position from the grid
    var random_image    = Math.floor(Math.random() * array.length) + 0; // grab a random image

    while ($.inArray(random_image, new_array.slice(0, 24)) > -1) {  // condition to avoid duplicate images
        random_image    = Math.floor(Math.random() * array.length) + 0;
    }

    $('#' + random_position).fadeOut(300, function() {  // change image
        $('#' + random_position).attr('src', 'images/banner/' + random_image + '.jpg');
        $('#' + random_position).fadeIn(300);
    });

    new_array[random_position - 1] = random_image;  // register the change

    return false;

}, 5000);

function shuffle(o){ //  shuffle function
for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多