我应该注意到我所有的 JavaScript 都在单独的 base.js 文件中。在下面的代码中我是
1) 选择一个div
2) 给它一个 id 和 onlcick 属性
3) 调用我紧接着声明的函数。
由于某种原因该功能失败。我试过把功能放在第一位,但仍然没有成功。目标是按下按钮时 div 背景和 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>
最佳答案
函数和变量声明都被提升到它们包含范围的顶部,函数首先被提升。
因此,您的代码等同于:
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>
关于javascript - 不引人注目地设置属性后功能失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36805112/