不引人注目地设置属性后函数失败

Function failing after unobtrusively setting attributes

本文关键字:函数 失败 属性 设置 引人注目      更新时间:2023-09-26

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