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

JavaScript开发骰子游戏时if else逻辑不生效问题求助

问题背景

做Udemy课程的JavaScript骰子游戏挑战项目时,页面重载随机生成骰子点数的功能运行正常,但新增的if else点数对比逻辑始终无法修改页面h1标签内容,预期要根据结果显示DRAW!/PLAYER 1 WINS!/PLAYER 2 WINS!。
附上原有项目代码:

原有HTML代码

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Dicee</title>
    <link rel="stylesheet" href="C:\Users\natan\Desktop\Web Development udemy\JavaScript\Dicee Challenge\styles.css">
    <link href="https://fonts.googleapis.com/css?family=Indie+Flower|Lobster" rel="stylesheet">
  </head>
  <body>
    <div class="container">
      <h1 class ="h1">Refresh Me</h1>
      <div class="dice">
        <p>Player 1</p>
        <img class="img1" src="C:\Users\natan\Desktop\Web Development udemy\JavaScript\Dicee Challenge\images\dice6.png" alt="dice6">
      </div>
      <div class="dice">
        <p>Player 2</p>
        <img class="img2" src="C:\Users\natan\Desktop\Web Development udemy\JavaScript\Dicee Challenge\images\dice6.png" alt="dice6">
      </div>
    </div>
    <script src="./js/index.js" charset="utf-8"></script>
  </body>
  <footer>
    www 🎲 App Brewery 🎲 com
  </footer>
</html>

原有JavaScript代码

function randomDice() {
  const randomNum1 = Math.floor(Math.random() * 6 + 1);
  const randomNum2 = Math.floor(Math.random() * 6 + 1);

  const img1Random = document.querySelector(".img1");
  img1Random.setAttribute("src", "./images/dice" + randomNum1 + ".png");

  const img2Random = document.querySelector(".img2");
  img2Random.setAttribute("src", "./images/dice" + randomNum2 + ".png");

  let doch1 = document.querySelector("h1").innerHTML

  if (randomNum1 === randomNum2) {
    doch1 = "DRAW!"
  } else if (randomNum1 > randomNum2) {
    doch1 = "PLAYER 1 WINS!"
  } else {
    doch1 = "PLAYER 2 WINS!"
  }
}

randomDice()
问题原因

代码里只把h1标签当前的innerHTML字符串值存到了普通变量doch1里,后续给doch1重新赋值只会修改这个独立的字符串变量,不会同步更新DOM里h1元素的实际内容,所以判断逻辑虽然执行了,但页面看不到变化。

修复方案

不要单独存h1的文本值,先获取h1的DOM元素引用,判断完点数后直接给元素的innerHTML属性赋值即可。
修复后的完整JS代码:

function randomDice() {
  const randomNum1 = Math.floor(Math.random() * 6 + 1);
  const randomNum2 = Math.floor(Math.random() * 6 + 1);

  const img1Random = document.querySelector(".img1");
  img1Random.setAttribute("src", "./images/dice" + randomNum1 + ".png");

  const img2Random = document.querySelector(".img2");
  img2Random.setAttribute("src", "./images/dice" + randomNum2 + ".png");

  // 获取h1DOM元素引用
  const h1Element = document.querySelector("h1");

  if (randomNum1 === randomNum2) {
    h1Element.innerHTML = "DRAW!"
  } else if (randomNum1 > randomNum2) {
    h1Element.innerHTML = "PLAYER 1 WINS!"
  } else {
    h1Element.innerHTML = "PLAYER 2 WINS!"
  }
}

randomDice()

额外优化提示:原有HTML里写死的C盘本地绝对路径(样式、图片的src)换设备运行会失效,建议和JS里的路径写法保持一致,改成相对路径。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 21:54:31