2011-06-14 43 views
-2
<html> 
    <head> 
     <title>test</title> 
     <script type="text/javascript"> 
      function start(){ 
       document.getElementById("first_div").onclick = function(){ 
        document.getElementById("another_div").style.color = "red";     
       }; 
      } 
     </script> 
    </head> 
    <body onload="start()"> 
     <div id="first_div">first</div> 
     <div id="anoter_div">second</div> 
    </body> 
</html> 

當我點擊first_div,發生錯誤:爲什麼在匿名函數中改變DOM屬性不起作用?

TypeError: Result of expression 'document.getElementById("another_div")' [null] is not an object. 

知道爲什麼這是不工作?

謝謝。

回答

5

你犯了一個錯字。變化:

document.getElementById("another_div") 
          ^

要:

document.getElementById("anoter_div") 

或者你可以改變你的div的名字,這可能是更好:

<div id="anoter_div">second</div> 

<div id="another_div">second</div> 
      ^

方法document.getElementById(..)無法找到元素並返回null,這就解釋了你得到的錯誤。

+0

或更好的是,更正DIV ID中的原始錯別字... :) – 2011-06-14 08:15:08

相關問題