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

JavaScript随机图片生成函数无法运行,求问题排查与解决

问题分析与修正

一、存在的问题

  • HTML按钮事件绑定错误:每个按钮写了两个onclick属性,浏览器只会执行第一个,第二个computerRandom()不会被触发。
  • JS随机索引计算错误:Math.floor(Math.random() * compImgs)是用随机数乘以数组对象本身,正确逻辑是乘以数组长度compImgs.length,否则会生成无效索引。
  • canvas元素获取方式错误:document.canvas不是合法的元素选择方式,需要通过getElementById等方法获取具体的canvas元素。
  • 冗余无效代码:var showImg = compImgs[showComp];这行代码中,showComp是图片路径字符串,用它作为数组索引会得到undefined,且这行无实际作用,可删除。

二、修正后的代码

JavaScript代码

function computerRandom(){
  var compImgs = ["rock1Computer.png", "paper1Computer.png", "scissors1Computer.png"];
  // 生成合法的数组随机索引
  var compRps = Math.floor(Math.random() * compImgs.length);
  // 获取页面中的canvas元素(假设元素id为compCanvas)
  const compCanvas = document.getElementById("compCanvas");
  if (compCanvas) {
    compCanvas.src = compImgs[compRps];
  }
};

HTML代码

<div class="playerBtn">
    <!-- 合并多个函数调用到同一个onclick属性,用分号分隔 -->
    <button type="button" onclick="showPRock(); computerRandom()" id="rockBtn">Rock</button>
    <button type="button" onclick="showPPaper(); computerRandom()" id="paperBtn">Paper</button>
    <button type="button" onclick="showPScissors(); computerRandom()" id="scissorsBtn">Scissors</button>
</div>
<!-- 补充对应的canvas元素,需与JS中获取的id一致 -->
<canvas id="compCanvas"></canvas>

额外提醒

  • 确保页面中存在id为compCanvas的canvas元素,否则JS无法找到目标元素设置图片。
  • 确认图片文件路径正确,保证浏览器能正常加载图片资源。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 03:37:29