2017-07-02 388 views
-1

嘗試編輯狀態DIV時出現奇怪的錯誤。TypeError:無法設置未定義的屬性'backgroundColor'

styleBox()函數應該通過更改顏色和backgroundColor來編輯狀態DIV。但是我每次運行函數時我得到這個錯誤:

TypeError: Cannot set property 'backgroundColor' of undefined 

它沒有意義的,我是因爲當我看到如果我選擇正確的股利,我沒有得到一個未定義的錯誤:

document.getElementById('status'); 
>> <div id=​"status" style>​</div>​ 

我認爲它與狀態DIV中的「樣式」有關,但不知道如何繼續。我看着here,但這與選擇類而不是ID有關。

我的代碼如下:

<!DOCTYPE html> 
<html> 
    <head> 
     <title> 
      Day 11 - Functions Visuals 
     </title> 

     <style> 
      #box { 
       width:200px; 
       height:200px; 
       background-color:black; 
      } 
     </style> 
    </head> 

    <body> 
     <div id="group"> 
      <button id="blue">Blue</button> 
      <button id="red">Red</button> 
      <button id="green">Green</button> 
      <div id="status" style=""></div> << -- This is what is tripping me up 
     </div> 

     <div id="box"></div> 

     <script type="text/javascript"> 



      // Create variables for each id 

      blueButton = document.getElementById('blue'); 
      redButton = document.getElementById('red'); 
      greenButton = document.getElementById('green'); 
      status = document.getElementById('status'); 
      box = document.getElementById('box'); 

      function styleBox() { 

       box.style.width = "50px"; 
       box.style.height = "50px"; 
       status.innerHTML = "The box is changed"; 
       status.style.backgroundColor = "#000000"; 
       status.style.color = "#FFF"; 
      }; 


     </script> 
    </body> 
</html> 
+2

被稱爲狀態*的全局變量*可能與https://developer.mozilla.org/en-US/docs/Web/API/Window/status –

+0

衝突謝謝@JaromandaX你是正確的。我不知道保留名稱列表https://www.w3schools.com/js/js_reserved.asp – Chef1075

回答

0

要回答我的問題,

的Javascript保留,但不能使用這些保留字作爲變量,標籤或函數名的話。

其中的一個詞是我稱之爲「變量」的「狀態」。更改變量名後我的代碼工作。

有關保留字的列表,請查看this列表。

+0

請不要參考w3schools,[* ECMA-262 *](http://ecma-international.org/ ecma-262/7.0/index.html#sec-reserved-words)是權威指南,[* MDN *](https://developer.mozilla.org/en-US/docs/Web/JavaScript)是一個非常有用的資源。請注意,* status *不是保留字,它是依賴於實現的(瀏覽器)*窗口*對象的屬性。如果您錯誤地使用了保留字,大多數環境都會通過錯誤消息告訴您。 – RobG

+0

下次會介紹。謝謝! – Chef1075

相關問題