不引人注目地设置属性后函数失败
Function failing after unobtrusively setting attributes
我应该注意,我所有的JavaScript都在单独的base.js文件中。在下面的代码中,我是
1) 选择一个div
2)给它一个id和onlcick属性
3)调用我紧随其后的函数。
由于某种原因,函数失败。我尝试将函数放在首位,但仍然没有成功。目标是当按下按钮时,divs 背景和 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 test() 函数失败了
- 不引人注目地设置属性后函数失败
- 按钮单击Javascript函数失败,但函数有效
- 当我在文本区域(MVC 4 Razor View)上加上引号时,JS长度函数失败
- 将模型的 urlRoot 重写为函数失败
- Ajax 表单提交进度函数失败
- 在页面加载/单击事件后,从 JS 文件 1 中的函数调用 JS 文件 2 中定义的函数失败
- 将函数引用传递给函数失败
- JavaScript 数组推送 Anon 函数失败
- 万一函数失败,什么是好的返回值
- Javascript 原型函数失败
- 如何防止 jQuery 函数在前面的函数失败时不运行
- jQuery - .ajax 使函数失败
- javascript:将键从for循环传递到另一个函数失败
- Javascript构造函数失败
- 在asp:dropdownlist中将变量传递给javascript函数失败
- jQuery.when:如果一个函数失败,会发生什么
- 奇怪的字符编码问题导致js函数失败或添加不需要的字符
- 当我传递参数时,从动态添加的html按钮调用javascript函数失败
- 自动滚动回调函数失败