Javascript 为每个图像选择随机图像

Javascript 为每个图像选择随机图像,javascript,dom,simple-html-dom,Javascript,Dom,Simple Html Dom,上面是我的代码。我目前已经用这种方式设置了javascript。当前代码有一个片段,其中图像从数组中的图像随机替换。我想要一个代码状态,用一个新的随机图像切换每个图像,而不是同时切换每个图像。我喜欢每次都是随机的,但我也希望每幅图片都是随机的。设置一个循环遍历每幅图像,选择一幅随机图像,然后分配给该图像: //Setting up the Array var arrayImg =['http://www.whattofix.com/images/PoliticalAnimal.jpg','ht

上面是我的代码。我目前已经用这种方式设置了javascript。当前代码有一个片段,其中图像从数组中的图像随机替换。我想要一个代码状态,用一个新的随机图像切换每个图像,而不是同时切换每个图像。我喜欢每次都是随机的,但我也希望每幅图片都是随机的。

设置一个循环遍历每幅图像,选择一幅随机图像,然后分配给该图像:

//Setting up the Array

var arrayImg =['http://www.whattofix.com/images/PoliticalAnimal.jpg','http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals26.jpeg','http://cdn.trendhunterstatic.com/thumbs/suit-animal-art-berkley-illustrations.jpeg','http://img1.etsystatic.com/016/1/7647665/il_340x270.411173311_ojy5.jpg'];

// creating the randomizing

var random = arrayImg[Math.floor(Math.random()*arrayImg.length)];


// image source looks for the attribute, by using the variable arraying
$('img').attr('src',random);

您可以使用回调函数和
attr
方法来计算每个元素的值:

var arrayImg =['http://www.whattofix.com/images/PoliticalAnimal.jpg','http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals26.jpeg','http://cdn.trendhunterstatic.com/thumbs/suit-animal-art-berkley-illustrations.jpeg','http://img1.etsystatic.com/016/1/7647665/il_340x270.411173311_ojy5.jpg'];

$("img").each(function() {
    var random = arrayImg[Math.floor(Math.random()*arrayImg.length)];
    $(this).attr('src',random);
});

什么意思?有时你会得到同样的图片?你是说你不想重复图片?
$('img').attr('src', function(){
  return arrayImg[Math.floor(Math.random()*arrayImg.length)];
});