【问题标题】:Why is my code only displaying incorrect even if I have the right answer?为什么即使我有正确的答案,我的代码也只显示不正确?
【发布时间】:2014-03-06 03:45:07
【问题描述】:

我正在编写一个快速程序来教自己函数的基础知识,除了 IF ELSE 语句之外,一切都正常。即使我使用正确的答案,它也总是显示不正确。我是否必须以某种方式使用数字的键值而不是实际数字?

<!doctype html>
<body>
<center>
<form Id="Input">
<input type="text" name="Input">
<input type="button" value="submit" ID="Button">
</form>
<script type="text/javascript">
Button.addEventListener("click", Answer);
var A = Math.floor(Math.random()*11);
var B = Math.floor(Math.random()*11);
var C = A +B;
var Input = document.getElementById('Input');
document.write(A + "+" + B + "=");
function Answer()
{
    if(Input.value == C)
    {
        alert("correct!");
    }
    else
    {
        alert("incorrect!");
    }
}

</script>
</body>
</html>

【问题讨论】:

  • 您的其他问题的延续? stackoverflow.com/questions/22213632/…
  • 有点,但这是一个不同的问题。
  • 如果它是关于同一个块代码,那么应该尽量把它放在同一个问题中

标签: javascript forms function math button


【解决方案1】:

Input 是表单元素的 id,你需要获取文本元素,所以通过它的 id Input 访问表单然后输入元素使用它的名字所以Input.Input 然后是它的值

function Answer() {
    if (Input.Input.value == C) {
        alert("correct!");
    } else {
        alert("incorrect!");
    }
}

演示:Fiddle


另一种方法是更改​​表单的 id 并将 id Input 分配给文本字段,如

<form Id="MyForm">
    <input type="text" name="Input" id="Input">
    <input type="button" value="submit" ID="Button">
</form>

然后

function Answer() {
    if (Input.value == C) {
        alert("correct!");
    } else {
        alert("incorrect!");
    }
}

演示:Fiddle

【讨论】:

  • 谢谢!这个工作太容易了!你能解释一下为什么这对我有用吗?它完全修复了它!
  • @user3385983 见上面的描述......当你说Input.value它试图访问form元素的value属性,这是未定义的
  • 谢谢!这可能会帮助我记住其中的一些东西以备将来使用!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-24
  • 2020-01-09
  • 1970-01-01
相关资源
最近更新 更多