首页 > 解决方案 > 在 1 个 div 标签中加载 1 个随机图像(可能是 10 个图像)

问题描述

我不是一个真正的程序员,需要一些帮助。我需要一个插入 div 标签的脚本,并且当页面从外部 js 文件加载时,在该 div 标签内有一个随机图像加载(来自 10 个列表)。

我搜索和搜索并尝试了不同的方法,但确实需要帮助。

谢谢

标签: jqueryimagerandom

解决方案


下面的解决方案使用了 jQuery,但是没有它也可以通过简单的方式实现

$(document).ready(function() {

  function randomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  var imageUrls = [
    "https://www.gstatic.com/webp/gallery3/1.sm.png",
    "https://www.gstatic.com/webp/gallery3/2.sm.png",
    "https://www.gstatic.com/webp/gallery3/3.sm.png"
  ];

  var randomImage = imageUrls[randomInt(0, imageUrls.length - 1)];

  $(".container").append("<img alt='" + randomImage + "' src='" + randomImage + "'</>");


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
</div>


更新 - 完整的 HTML 有效页面内的相同答案

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
    </script>    
    <script type="text/javascript">


        /**
        * Loads a random number
        */
        function randomInt(min, max) {
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }

        // List of urls
        var imageUrls = [
            "https://www.gstatic.com/webp/gallery3/1.sm.png",
            "https://www.gstatic.com/webp/gallery3/2.sm.png",
            "https://www.gstatic.com/webp/gallery3/3.sm.png"
        ];

        function loadRandomImage() {
            var randomImage = imageUrls[randomInt(0, imageUrls.length - 1)];
            $(".container").append(
                    "<img alt='" + randomImage + "' src='" + randomImage + "'</>");
        }

        // This function executes when the DOM is ready, 
        // e.g., when the entire page is loaded
        $(document).ready(function() {
            loadRandomImage()
        });
    </script>
</head>
<body>
    <div class="container">
    </div>
</body>
</html>

推荐阅读