页面加载中的随机图像 [英] Random Images on page load
问题描述
我目前正在建立一个站点,他们希望这些站点在加载时显示不同的图像.到目前为止,我已经能够针对这些目标并将它们随机化,但是它将相同的图像应用于所有项目.如果您能看到我要去哪里错了,那太好了
I am currently building a site whereby they would like each image on load to display different images. I have so far been able to target these and randomise them but it is applying the same image to all of the items. If you could see where I'm going wrong it would be great
var description = [
"http://placehold.it/300x300",
"http://placehold.it/200x200",
"http://placehold.it/100x100"
];
var size = description.length
var x = Math.floor(size*Math.random())
$('.item img').each(function() {
if($("img").hasClass("people")) {
$(this).attr("src",description[x]);
}
});
推荐答案
您的代码似乎有2个问题:
There seems to be 2 problems with your code:
-
您的随机数在
.each
循环之外.因此,为什么所有图像都得到相同的图像.
Your randomizer is outside the
.each
loop. Hence why all your images get the same image.
所有图像都具有src属性,即使没有people
类的图像也是如此.
All images get the src attribute, even those without the people
class.
您几乎正确地做到了.尝试使用以下更正所做的 小提琴 或下面的演示.
You nearly got it right though. Try a fiddle I made with these corrections, or the demo below.
var description = [
"http://placehold.it/300x300",
"http://placehold.it/200x200",
"http://placehold.it/100x100"
];
var size = description.length;
$('.item img').each(function() {
var x = Math.floor(size * Math.random()); //move random inside loop
if ($(this).hasClass("people")) { //replace "img" with "this"
$(this).attr("src", description[x]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item">
<img src="" class="people">
</div>
<div class="item">
<img src="" class="people">
</div>
<div class="item">
<img src="">
</div>
<div class="item">
<img src="" class="people">
</div>
请注意,这里有4个items
,但是其中一个没有people
类,并且正确地没有设置为图像(只有3个是).
Note that there are 4 items
here, but one is without the people
class and correctly isn't set to an image (only 3 are).
这篇关于页面加载中的随机图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!