2010-10-12 57 views
2

出于某种原因,我得到一个document.getElementById('id') is null JS错误线路7与下列标记和脚本:的document.getElementById(“身份证”)是空的JavaScript错误

<!DOCTYPE html> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Quadratic Root Finder</title> 
<script> 
document.getElementById('calculate').onclick = function calculateQuad() 
{ 
    var inputa = document.getElementById('variablea').value; 
    var inputb = document.getElementById('variableb').value; 
    var inputc = document.getElementById('variablec').value; 

    root = Math.pow(inputb,2) - 4 * inputa * inputc; 
    root1 = (-inputb + Math.sqrt(root))/2*inputa 
    root2 = (-inputb + Math.sqrt(root))/2*inputa 

    document.getElementById('root1').value = root1; 
    document.getElementById('root2').value = root2; 
    if(root<'0') 
    { 
     alert('This equation has no real solution.') 
    } 
    else { 
     if(root=='0') 
     { 
      document.getElementById('root1').value = root1 
      document.getElementById('root2').value = 'No Second Answer' 
     } 
     else { 
      document.getElementById('root1').value = root1 
      document.getElementById('root2').value = root1 
      } 
     } 
}; 
document.getElementById('erase').onlick = this.form.reset(); 
</script> 
<style> 
#container 
{ 
    text-align: center; 
} 
</style> 
</head> 

<body> 
<div id="container"> 
<h1>Quadratic Root Finder!</h1> 
<form id="form1"> 
    a:<input id="variablea" value="" type="text"> 
    <br/> 
    b:<input id="variableb" value="" type="text"> 
    <br /> 
    c:<input id="variablec" value="" type="text"> 
    <br /> 
    <input id="calculate" value="Calculate!" type="button"> 
    <input id="erase" value="Clear" type="button"> 
    <br /> 
    <br /> 
    Roots: 
    <br /> 
    <input id="root1" type="text" readonly> 
    <br /> 
    <input id="root2" type="text" readonly> 
</form> 
</div> 
</body> 
</html> 

这里有什么真正的问题?

+0

possible dupl [为什么jQuery或DOM方法如\'getElementById \'找不到元素?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-如getelementbyid-not-the-element) – Bergi 2013-02-13 19:24:58

回答

0

在javascript实际运行的时候,没有元素的id为'calculate'。您需要确保在创建所需元素后运行JavaScript。我的建议是使用像jQuery一样的通用JavaScript框架。然后你只需附上你的脚本对DOM准备运行:

$(document).ready(function() { 
    // Handler for .ready() called. 
}); 
+0

哇,我一直忘记这些简单的错误,但现在我得到了你。现在我想到了,jQuery会让这个选择业务比getElementById'垃圾更容易,但我试图接触普通的JS,但我仍然可以使用你的建议,thx! – Qcom 2010-10-12 02:58:18

+1

这似乎有一个巨大的推动使用jQuery。 – Strawberry 2010-10-12 02:58:51

+3

我认为这不是一个jQuery的问题。 – 2010-10-12 03:06:31

2

如果你不喜欢,包括jQuery的,然后​​将工作也没关系。

2

或者:window.onload = function(){}作品,以及

6

这的确是null。你的元素在页面上还不存在。

或者:

  • 将下面的代码你<script>
  • 添加window.onload事件。
0
  1. 使用windows.onload
  2. 在“body end tag”下面添加链接文件脚本或脚本