我遇到了Javascript问题。它说“TypeError:document.forms.inputs is undefined”

时间:2017-04-06 12:37:24

标签: javascript html

我正在努力完成这项工作,而且我无法从其他任何有价值的资源中获得帮助。我想主要的问题是引用DOM格式的变量。 我在这里有代码(我没有共享CSS,因为它在这个错误中可能不重要)

`

<script>
var a, b, c;
a = document.forms["inputs"]["deg_2"].value;
b = document.forms["inputs"]["deg_1"].value;
c = document.forms["inputs"]["deg_0"].value;
  var D = b^2 - 4*a*c;

  var ans1 = (-b + sqrt(D)/2*a);
  var ans2 = (-b - sqrt(D)/2*a);


function result(){

    document.getElementById('answer1').innerHTML = ans1;
    document.getElementById('answer2').innerHTML = ans2;
}
</script>
</head>
<body>
  <div class = "head">
<h1 class = "head">  Quad Root Finder </h1>
  </div>
  <div class = "message">
<h3 class = "message">  Hello user, I am making this Quad Root Finder as one of my starting project. </h3>
  </div>
<div class = "derivative">
<form name = "inputs">
    <input type="text" name = "deg_2" ></input><lable for = "x^2"> x^2 +  </lable>
    <input type = "text" name = "deg_1"></input><lable for = "x"> x +  </lable>
    <input type = "text" name = "deg_0"></input><lable for = "constant"> </lable><br><br>
    <button onclick="result()"> Find Roots </button>
</form>
</div>
<p class = "answer_title">
Answer:
</p>
<div class = "answer">
    <h3 id = "answer1"> </h3>
    <h3 id = "answer2"> </h3>
</div>
</body>

`

1 个答案:

答案 0 :(得分:0)

您收到错误的原因是您的JavaScript代码位于HTML页面的顶部。这意味着它将在您的HTML被解析之前执行。因此,当您的代码运行时,就浏览器的DOM而言,这些元素并不存在。

正如问题的评论中所指出的那样,您应该在result函数中移动所有逻辑,否则ans1ans2将只有原始值页面加载。

作为一种好的做法,您还应该将JavaScript移到HTML的底部,以便在DOM执行之前加载它。

<body>
    // All your other HTML
    <script>
        function result(){
            var a, b, c;
            a = document.forms["inputs"]["deg_2"].value;
            b = document.forms["inputs"]["deg_1"].value;
            c = document.forms["inputs"]["deg_0"].value;
            var D = b^2 - 4*a*c;

            var ans1 = (-b + sqrt(D)/2*a);
            var ans2 = (-b - sqrt(D)/2*a);
            document.getElementById('answer1').innerHTML = ans1;
            document.getElementById('answer2').innerHTML = ans2;
        }
    </script>
</body>