javascript - 页面加载时的随机图像

标签 javascript jquery if-statement random each

我目前正在构建一个站点,他们希望加载的每个图像都显示不同的图像。到目前为止,我已经能够定位这些并随机化它们,但它正在对所有项目应用相同的图像。如果你能看到我哪里出错了,那就太好了

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/

相关文章:

javascript - 具有多个不同输入的文件上传进度条(MVC)

jquery - 如何禁用所有提交按钮然后重新启用特定按钮?

c# - 使用 for 循环获取动态创建的 asp 控件 ids(values)

Javascript if/else 问题

ms-access - VB中日期等于或小于x

javascript - 从本地网络应用程序连接到 Google 的 apprtc.appspot.com。可能的?

javascript - FullCalendar - 删除选定的事件

c# - 使用 BoundField 时对特定 Gridview 列的 JQuery 搜索

c# - 如何在不为每种情况使用 if 和 switch 语句的情况下重构链中的数百个条件?

javascript - 使用 Javascript 将自定义查询字符串变量拉入隐藏表单字段