2017-07-02 29 views
-1

ステータスDIVを編集しようとすると奇妙なエラーが発生します。TypeError:未定義の 'backgroundColor'プロパティを設定できません

styleBox()関数は、colorとbackgroundColorを変更してステータスDIVを編集する必要があります。

:しかし、私はこのエラーを取得する機能を実行するたび:私が正しく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

status *と呼ばれるグローバル変数がhttps://developer.mozilla.org/en-US/docs/Web/API/Window/statusと競合する可能性があります。 –

+0

ありがとう@JaromandaXあなたは正しいです。私は予約された名前リストhttps://www.w3schools.com/js/js_reserved.aspについて知らなかった – Chef1075

答えて

0

自分の質問に答えるために、

Javascriptが変数、ラベル、または関数名としてこれらの予約語を使用することができない単語を予約しています。

これらの単語のうちの1つは、私が自分の変数の名前を付けた「ステータス」です。変数名を変更した後、私のコードはうまくいった。

予約語の一覧については、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

関連する問題