Javascript 闭包在html脚本标记中正常工作吗?
我创建了一个简单的HTML,如下所示:Javascript 闭包在html脚本标记中正常工作吗?,javascript,html,Javascript,Html,我创建了一个简单的HTML,如下所示: <!DOCTYPE HTML> <html> <head> <script> function initElement(){ var p = document.getElementById('pp'); p.setAttribute("style", "color:pink"); p.onclick = x;
<!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>
函数initElement(){
var p=document.getElementById('pp');
p、 setAttribute(“样式”,“颜色:粉色”);
p、 onclick=x;
}
函数x(){
p、 setAttribute(“style”,“color:brown”);//不起作用,因为未定义p
document.getElementById('pp').setAttribute(“样式”,“颜色:棕色”);//有效
};
笨蛋
这是用于测试的
你好
为什么不从闭包加载
p
?这是使用以下示例文件构建的,js中的变量是函数作用域,因此在函数x
中,变量p
将是未定义的(因为它未在作用域中声明或初始化)。如果在这两个函数之外声明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>
var-p;
函数initElement(){
p=document.getElementById('pp');
p、 setAttribute(“样式”,“颜色:粉色”);
p、 onclick=x;
}
函数x(){
p、 setAttribute(“style”,“color:brown”);//p现在在范围内,所以应该可以工作
};
笨蛋
点击我
正如torazaburo在注释中所述,变量在其函数声明之外不可用,因此代码不起作用。下面的更改修复了它。当在initElement
中声明x()
时,将发生闭包
<!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>
函数initElement(){
var p=document.getElementById('pp');
p、 setAttribute(“样式”,“颜色:粉色”);
p、 onclick=x;
函数x(){
p、 setAttribute(“样式”、“颜色:棕色”);
//document.getElementById('pp').setAttribute(“样式”,“颜色:棕色”);
};
}
笨蛋
这是用于测试的
你好
它不起作用,因为它不是一个闭包。这样写:p.onclick=function(){p.setAttribute(…)…}
它就会工作。这里没有闭包。只有一个函数。函数内部声明的变量不能从函数外部使用。