简体   繁体   English

如何从数组中选择随机图像并将其用作 javascript 和 html 中其他图像的来源

[英]How do I choose a random image from an array and use it as a source for other images in javascript and html

I am trying to make a website and I need random images to be generated and then used as an input button thingy.我正在尝试制作一个网站,我需要生成随机图像,然后用作输入按钮。

When I try to use the results of the thing the image does not show up.当我尝试使用图像不显示的结果时。

The thing i need help with is displaying the image bc the code that picks the random image like has it under a name but idk how to use to name as a source for a button thing我需要帮助的事情是显示图像 bc 选择随机图像的代码就像在名称下一样,但我不知道如何使用名称作为按钮事物的来源

I want the generated image to replace the button if that makes any sense如果有任何意义,我希望生成的图像替换按钮

I believe you're trying to do this:我相信你正在尝试这样做:

HTML: HTML:

<html>
  <body>
    <a href="#" onclick="alert('You clicked!')">
      <img src="" id="button_img" style="height: 100px;width: 100px;">
    </a>
  </body>
</html>

JS:记者:

<script>

  //array of links for images
  var array_of_images = [
    "https://www.pngitem.com/pimgs/m/97-974332_yellow-duck-png-download-image-transparent-background-rubber.png",
    "https://www.shareicon.net/data/256x256/2015/07/31/78089_make_512x512.png",
    "https://www.pngitem.com/pimgs/m/97-974413_rubber-duck-png-transparent-background-duck-clipart-png.png"
    ];

  //generate random number form 0-3
  var randomNum = Math.floor(Math.random()*3);

  //using the random number to choose a link from the array
  document.getElementById('button_img').src = array_of_images[randomNum];

</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript! 如何使用随机数组选择随机数组? - Javascript! How do I choose a random array WITH a random array? 每次页面刷新时,如何将JavaScript文件中的随机图像加载到HTML中? - How do I load a random image from an array in a JavaScript file into HTML every time the page refreshes? 如何从 javascript 中的 object 中选择随机嵌套属性? - How do i choose a random nested property from an object in javascript? 使用JavaScript在页面加载时选择随机图像,但使该随机图像随其加载第二个特定图像 - Use JavaScript to choose random images on page load, but make this random image load a second specific image with it 如何使用同位素使用Javascript从数组中过滤单个随机图像 - How to use Isotope to filter a single random image with Javascript from an array 如何在 html 中显示来自 Javascript 数组的随机引用? - How can I display an random quote from an Javascript Array in html? Javascript从数组中选择随机数并按字母顺序排列 - Javascript to choose random from array and alphabetize 如何从Javascript数组中提取图像并将其放入HTML? - How do I pull images from a Javascript array and place them into HTML? 如何从数组中选择一个随机项? - How can i choose one random item from an array? 如何过滤到数组并从中选择一个随机 ID? - How can I filter to an array and choose a random Id from it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM