2010-10-12 62 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」下面添加鏈接文件腳本或腳本