我創建了一個簡單的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
它不起作用,因爲它不是閉包。這樣寫:'p.onclick = function(){p.setAttribute(...)...}'它會起作用。 – axiac
這裏沒有關閉。只有一個功能。在函數內聲明的變量不在外部可用。 – 2017-03-18 07:59:34