我应该注意,我的所有JavaScript都在单独的base.js文件中。在以下代码中我是
1)选择div
2)给它一个id和onlcick属性
3)调用我之后立即声明的函数。
由于某种原因,该功能失败。我已经尝试将该功能放在第一位,但仍然没有成功。目标是按下按钮时divs background和innerHTML会改变。任何想法为什么这不起作用?
var expand = document.querySelector("body div:first-child");
expand.setAttribute("id", "expand");
expand.addEventListener('click', expand);
function expand() {
"use strict";
expand.style.backgroundColor = "red";
document.getElementById("expand").innerHTML = "hi";
}
body{ text-align:center }
body div:first-child{
float:left;width:28px;padding:5px;background:#fff;color:#666;cursor:pointer;
font-size:150%
}
body div:first-child:hover{
background:#222; color:#eee
}
body div:first-child:active{background:#444; color:#fff}
<!doctype html>
<html>
<body>
<div>+</div>
<script src="js/base.js"></script>
</body>
</html>
答案 0 :(得分:1)
函数和变量声明都被提升到其包含范围的顶部,并首先提升函数。
因此,您的代码相当于:
function expand() { //hoisted
"use strict";
expand.style.backgroundColor = "red";
document.getElementById("expand").innerHTML = "hi";
}
var expand; //hoisted
expand = document.querySelector("body div:first-child");
expand.setAttribute("id", "expand");
expand.addEventListener('click', expand);
基本上,变量expand
覆盖您的函数expand
。
要修复它,只需为您的函数指定一个不同的名称:
var expand = document.querySelector("body div:first-child");
expand.setAttribute("id", "expand");
expand.addEventListener('click', fexpand);
function fexpand() {
"use strict";
expand.style.backgroundColor = "red";
document.getElementById("expand").innerHTML = "hi";
}
body{ text-align:center }
body div:first-child{
float:left;width:28px;padding:5px;background:#fff;color:#666;cursor:pointer;
font-size:150%
}
body div:first-child:hover{
background:#222; color:#eee
}
body div:first-child:active{background:#444; color:#fff}
<!doctype html>
<html>
<body>
<div>+</div>
<script src="js/base.js"></script>
</body>
</html>