错误代码展示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <style>
    div {
      width: 200px;
      height: 200px;
      background: #58a;
    }
  </style>
</head>
<body>
  <div id="ad"></div>
  <script>
    let ad = document.querySelector("#ad");
    ad.addEventListener("click",function(){
      setTimeout(function(){
        console.log(this);
        this.style.background = "red";
      },1000)
    })
  </script>
</body>
</html>

运行结果:

报错,原因:输出this的结果window,表名当前的this是执行window的

解决方案一:

使用_this保留当前事件下的this,代码展示
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <style>
    div {
      width: 200px;
      height: 200px;
      background: #58a;
    }
  </style>
</head>
<body>
  <div id="ad"></div>
  <script>
    let ad = document.querySelector("#ad");
    ad.addEventListener("click",function(){
      let _this = this;
      setTimeout(function(){
        _this.style.backgroundColor = "red";
        // this.style.background = "red";
      },1000)
    })
  </script>
</body>
</html>

解决方案二

使用箭头函数,原因是箭头函数不绑定this,它会捕获其所在(即当前定义的位置)中的this值,作为自己的this值,代码展示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <style>
    div {
      width: 200px;
      height: 200px;
      background: #58a;
    }
  </style>
</head>
<body>
  <div id="ad"></div>
  <script>
    let ad = document.querySelector("#ad");
    ad.addEventListener("click",function(){
      setTimeout(() =>{
        this.style.backgroundColor = "red";
      },1000)
    })
  </script>
</body>
</html>
posted on 2021-05-20 15:12  文种玉  阅读(130)  评论(0编辑  收藏  举报