2017-03-18 68 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得到從封閉裝?這是使用以下示例文件https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onclick

+0

它不起作用,因爲它不是閉包。這樣寫:'p.onclick = function(){p.setAttribute(...)...}'它會起作用。 – axiac

+2

這裏沒有關閉。只有一個功能。在函數內聲明的變量不在外部可用。 – 2017-03-18 07:59:34

回答

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

變量在JS是功能在功能x可變p作用域所以將undefined(因爲它是未聲明或在範圍初始化)構成。如果你在兩個函數之外聲明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>