【问题标题】:Inner HTML not changing from if statement?内部 HTML 没有从 if 语句改变?
【发布时间】:2022-12-01 06:13:23
【问题描述】:

我正在尝试制作一个数字猜谜游戏,并正在制作一个带有提交按钮的输入文本框。当按下按钮时,它应该根据答案检查其中的值是正确还是不正确。当我点击提交时,它什么也没做。

HTML

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>replit</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <script src="script.js"></script>
    <p id="numberGen">#</p>
    <button onclick="document.getElementById('numberGen').innerHTML = getRndInteger(1,10)">Click Me</button>
    <input id="inputValue" value="|" type="text">
    <button onclick="matchRndInput()">Submit Text</button>
    <p id="answer">#</p>


    <!--
  This script places a badge on your repl's full-browser view back to your repl's cover
  page. Try various colors for the theme: dark, light, red, orange, yellow, lime, green,
  teal, blue, blurple, magenta, pink!
  -->
    <script src="https://replit.com/public/js/replit-badge.js" theme="green" defer></script>
</body>

</html>
const value = document.getElementById("inputValue");
function getRndInteger(min, max) {
    var rnd = Math.floor(Math.random() * (max - min + 1)) + min;
    return rnd
}
function getTextValue() {
    return inputValue.value;
}
function matchRndInput() {
    if (rnd == inputValue.value) {
        document.getElementById('answer').innerHTML = "Correct";
    } else if (rnd < inputValue.value) {
        document.getElementById('answer').innerHTML = "Too low";
    } else if (rnd > inputValue.value) {
        document.getElementById('answer').innerHTML = "Too high";
    } else {
        document.getElementById('answer').innerHTML = "Wrong";
    }
}

任何帮助将不胜感激,谢谢!

我已经检查了所有变量名并仔细检查没有语法错误。

【问题讨论】:

  • document.getElementById('answer'). = "Correct";应该是document.getElementById('answer').innerHTML = "Correct";
  • matchRndInput() 上下文中的 rnd 是什么?检查您的控制台是否有错误。

标签: javascript html


【解决方案1】:
  1. 您的&lt;script&gt; 标签应该在您的&lt;head&gt; 标签中而不是您的&lt;body&gt; 标签中。
  2. 您需要使用element.innerHTML 来编辑元素的 innerHTML。
  3. 您还需要引用您的 getRndInteger 函数,而不是仅在您的 if 语句中使用 rnd

【讨论】:

  • 抱歉,我正在尝试使用 innerText 却忘了忘记改回来
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-26
  • 1970-01-01
  • 2013-06-16
  • 2015-08-17
  • 2022-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多