You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery多Div随机图片数组问题求助:所有Div复用最后一个数组

问题解决:每个随机图片容器独立加载对应数组内的图片

问题原因

你当前的代码里,每个<script>标签中声明的var images是全局变量。浏览器按顺序执行页面脚本时,后面的images变量会直接覆盖前面的,导致最后遍历所有.random-image-container时,images始终指向最后一个声明的数组,所以所有容器都会加载同一组图片。


解决方案1:使用data-*属性存储图片数组(推荐)

这种方法不需要全局变量,直接把每个容器对应的图片数组存在HTML的自定义属性中,更符合规范且易于维护。

修改后的HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<article class="grid-item">
  <div class="random-image-container" data-images='["IMG/1.jpg", "IMG/2.jpg"]'>
  </div>
</article>
<article class="grid-item">
  <div class="random-image-container" data-images='["IMG/3.jpg", "IMG/4.jpg"]'>
  </div>
</article>
<article class="grid-item">
  <div class="random-image-container" data-images='["IMG/5.jpg", "IMG/6.jpg"]'>
  </div>
</article>
<article class="grid-item">
  <div class="random-image-container" data-images='["IMG/7.jpg", "IMG/8.jpg"]'>
  </div>
</article>

修改后的JS:

$('.random-image-container').each(function() {
  const container = $(this);
  // 解析data-images属性中的JSON数组
  const images = JSON.parse(container.data('images'));
  // 随机选取一张图片的地址
  const randomImgSrc = images[Math.floor(Math.random() * images.length)];
  // 创建img元素并添加到当前容器
  $('<img class="random-image" src="' + randomImgSrc + '">').appendTo(container);
})

解决方案2:将数组绑定到容器元素上(无需大幅修改原有HTML结构)

如果不想调整HTML的结构,可以把每个脚本中的数组直接绑定到对应的容器元素上,避免全局变量覆盖。

修改后的HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<article class="grid-item">
  <div class="random-image-container">
    <script>
      // 把数组绑定到当前脚本的父容器元素上
      document.currentScript.parentElement.images = ['IMG/1.jpg', 'IMG/2.jpg'];
    </script>
  </div>
</article>
<article class="grid-item">
  <div class="random-image-container">
    <script>
      document.currentScript.parentElement.images = ['IMG/3.jpg', 'IMG/4.jpg'];
    </script>
  </div>
</article>
<article class="grid-item">
  <div class="random-image-container">
    <script>
      document.currentScript.parentElement.images = ['IMG/5.jpg', 'IMG/6.jpg'];
    </script>
  </div>
</article>
<article class="grid-item">
  <div class="random-image-container">
    <script>
      document.currentScript.parentElement.images = ['IMG/7.jpg', 'IMG/8.jpg'];
    </script>
  </div>
</article>

修改后的JS:

$('.random-image-container').each(function() {
  const container = $(this);
  // 获取绑定在当前容器元素上的images数组
  const images = container[0].images;
  const randomImgSrc = images[Math.floor(Math.random() * images.length)];
  $('<img class="random-image" src="' + randomImgSrc + '">').appendTo(container);
})

内容的提问来源于stack exchange,提问作者mmdwc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 11:10:35