2017-03-18 8 views
-3

ので、同様に、私は、簡単なHTMLを作成しました:HTMLスクリプトタグでクロージャは正常に機能しますか?

<!DOCTYPE HTML> 
<html> 
<head> 
    <script> 
     function initElement(){ 
      var p = document.getElementById('pp'); 
      p.setAttribute("style", "color:pink"); 
      p.onclick = x; 
     } 
     function x(){ 
      p.setAttribute("style", "color:brown"); // Doesnt work because p is not defined 
      document.getElementById('pp').setAttribute("style", "color:brown"); // works 
     }; 
    </script> 
</head> 
<body onload="initElement()"> 
    <h1> Dummy <h1> 
     <p id="pp"> this is for testing </p> 
     <button id="dummy"> Hello! </button> 
</body> 
</html> 

p閉鎖からロードされません。なぜ?これは、次の例では、jsの中https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onclick

+0

閉鎖ではないため動作しません。 'p.onclick = function(){p.setAttribute(...)...}'のように書くとうまくいきます。 – axiac

+2

ここにクロージャはありません。関数だけがあります。関数の中で宣言された変数は、外部からは利用できません。 –

答えて

0

コメント内でtorazaburoが驚いたように、変数は関数宣言の外では使用できないため、コードは機能しません。以下の変更により修正されています。閉鎖は、x()initElementの内部で宣言されたときに発生します。

<!DOCTYPE HTML> 
<html> 
<head> 
    <script> 
     function initElement(){ 
      var p = document.getElementById('pp'); 
      p.setAttribute("style", "color:pink"); 
      p.onclick = x; 
      function x(){ 
       p.setAttribute("style", "color:brown"); 
       // document.getElementById('pp').setAttribute("style", "color:brown"); 
      }; 
     } 
    </script> 
</head> 
<body onload="initElement()"> 
    <h1> Dummy <h1> 
     <p id="pp"> this is for testing </p> 
     <button id="dummy"> Hello! </button> 
</body> 
</html> 
0

変数のファイルを使用して構築された機能は、(それがスコープ内で宣言または初期化されていないとして)機能でx変数pundefinedになりそうスコープされています。 pを両方の関数の外に宣言すると、pが両方の関数のスコープに入るため、機能するはずです。

<!DOCTYPE HTML> 
<html> 
<head> 
    <script> 
     var p; 
     function initElement(){ 
      p = document.getElementById('pp'); 
      p.setAttribute("style", "color:pink"); 
      p.onclick = x; 
     } 
     function x(){ 
      p.setAttribute("style", "color:brown"); // p is now in scope so should work 
     }; 
    </script> 
</head> 
<body onload="initElement()"> 
    <h1> Dummy <h1> 
     <p id="pp"> Click me!</p> 
</body> 
</html> 
関連する問題