JS问题,现在尝试使用闭包实现变量,但是无效

问题描述

我希望点击t1

第一次输出a是1

第二次输出a是2

保留a的数值

现在尝试使用闭包实现,但是无效

具体代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    .t1 {
      width: 500px;
      height: 200px;
      background: #0C9A9A;
    }
  </style>
</head>
<body>

<div>
  <div class="t1">
    按钮
  </div>
</div>

<script>
  window.onload = function () {
    initClickEven()
  }

  function initClickEven() {
    // document.getElementsByClassName('t1')[0].onclick = function() {
    //   console.log(123)
    // }
    document.getElementsByClassName('t1')[0].onclick = function () {
      console.log('t1');
      handle(123);
    }
  }

  (function handle (data) {
    var a = 0
    return function () {
      a = a+1
      console.log(data, ' == ', a)
    }
  })();
</script>
</body>
</html>

感谢楼下提供思路

<script>
  window.onload = function () {
    initClickEven()
  }

  function initClickEven() {
    // document.getElementsByClassName('t1')[0].onclick = function() {
    //   console.log(123)
    // }
    document.getElementsByClassName('t1')[0].onclick = function () {
      console.log('t1');
      handle(321);
    }
  }

  var handle = (function () {
    var a = 0
    return function (data) {
      a = a+1
      console.log(data, ' == ', a)
    }
  })();
</script>
阅读 1.5k
1 个回答
window.onload = function () {
    initClickEven()
  }

  function initClickEven() {
    // document.getElementsByClassName('t1')[0].onclick = function() {
    //   console.log(123)
    // }
    document.getElementsByClassName('t1')[0].onclick = function () {
      console.log('t1');
      handle();
    }
  }

  var handle = (function (data) {
    var a = 0
    return function () {
      a = a+1
      console.log(data, ' == ', a)
    }
  })(123);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题