javascript - 不引人注目地设置属性后功能失败

标签 javascript html css function

我应该注意到我所有的 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/

相关文章:

javascript - Watchify with gulp 不起作用

javascript - Wordpress自定义表单输入检查

javascript - IE(移动)不显示触摸子元素

jquery - :before gets hidden when setting overflow to scroll/hidden 里面的内容

javascript - 如何在 JS 中将字符串(带前缀的数字)转换为 Double/Float

Javascript 动态表单字段

html - 多个行 block 元素

javascript - Jquery冲突: draggable and target collision event

javascript - 我如何将 css 转换添加到我的 Jquery 对话框?

html - 为什么我的导航相对于浏览器的宽度不是 100%