问题描述
我希望点击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>