我目前正在构建一个站点,他们希望加载的每个图像都显示不同的图像。到目前为止,我已经能够定位这些并随机化它们,但它正在对所有项目应用相同的图像。如果你能看到我哪里出错了,那就太好了
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
没有改变。您可以使用 setTimeout()
在 $.each()
内将数组的随机元素插入一个没有重复的数组;使用选择器 $(".item img.people")
设置 <img>
src
与 .attr(function)
迭代原始选择器集合中的所有元素
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>
关于javascript - 页面加载时的随机图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39993152/