[英]Random Images on page load
我目前正在建立一个网站,他们希望每个图像在加载时显示不同的图像。 到目前为止,我已经能够定位这些并随机化它们,但它将相同的图像应用于所有项目。 如果你能看到我出错的地方就会很棒
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]);
}
});
x
不会改变。 你可以在$.each()
使用setTimeout()
将数组的随机元素推送到没有重复的数组; 利用selector $(".item img.people")
使用.attr(function)
设置<img>
src
,它迭代原始选择器集合中的所有元素
var description = [ "http://placehold.it/300x300", "http://placehold.it/200x200", "http://placehold.it/100x100" ]; var arr = []; $.each(description, function(i, el) { setTimeout(function() { arr.push(el); if (arr.length === description.length) { $(".item img.people") .attr("src", function(i, src) { return arr[i] }) } }, 1 + Math.floor(Math.random() * 5)) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <div class="item"> <img class="people" alt=""> <img class="people" alt=""> <img class="people" alt=""> </div>
你的代码似乎有两个问题:
你的随机数.each
在.each
循环之外。 因此,为什么所有图像都得到相同的图像。
所有图像都获得src属性,即使是那些没有people
属性。
你几乎把它弄好了。 试试我用这些修正或下面的演示制作的小提琴 。
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个)。
您不应该全局定义随机数。 可能会低于代码将帮助您。
var description = [
"http://placehold.it/300x300",
"http://placehold.it/200x200",
"http://placehold.it/100x100"
];
var size = description.length;
var x=0;
$('.item img').each(function() {
x = Math.floor(size*Math.random());
if($(this).hasClass("people")) {
$(this).attr("src",description[x]);
}
});
您的代码中有一些错误。 你定义if($("img".
并检查第一个img
但你想要每个img)
var description = [
"http://placehold.it/300x300",
"http://placehold.it/200x200",
"http://placehold.it/100x100"
];
var size = description.length
$('.item img').each(function(i,e) {
var x = Math.floor(Math.random() * size)
if($(this).hasClass("people")) {
$(this).attr("src",description[x]);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.