eventListener中的JavaScript闭包 [英] JavaScript closure within eventlistener

查看:164
本文介绍了eventListener中的JavaScript闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < button> test< / button> 
< button> test< / button>
< button> test< / button>
< button> test< / button>
< button> test< / button>
< script>
var nodes = document.getElementsByTagName('button');
function clicked(i){
console.log('pass');

// Closure
// return function(){
// console.log(i);
//}

}
for(var i = 0; i nodes [i] .addEventListener ',clicked(i));
}
< / script>

我尝试完全理解js闭包,上面的函数添加了监听器到按钮。它控制台日志通过5次,然后什么都不做,当按钮单击。但如果我取消注释闭包位(返回),console.log将回声i,但不是日志通过。我确实找到相关的答案,但我不明白为什么闭包onclick不记录'通过的字符串,当按钮点击,而不是注销 i 。 >

你在这里做的是直接调用函数 clicked 而不是将其设置为事件处理程序。


当按钮被点击时,close onclick不会记录'pass'字符串,而是注销i。


/ p>

  return function(){
console.log(i);
}

为什么除了 i



创建此闭包的函数应在页面初始化期间记录pass五次(因为在循环中调用五次,



$ b

您可以使用 bind

  nodes [i] .addEventListener('click',clicked.bind(nodes [i],i) 

这将给你 i 到函数,这样你可以做

  console.log(pass,i); 


<button>test</button>
<button>test</button>
<button>test</button>
<button>test</button>
<button>test</button>
<script>
var nodes = document.getElementsByTagName('button');
function clicked(i){
    console.log('pass');

    // Closure
    // return function(){
    //  console.log(i);
    // }

}
for (var i = 0; i < nodes.length; i++) {
   nodes[i].addEventListener('click', clicked(i));
}
</script>

I am try to have a fully understanding on js closure, the above function add even listener to the buttons. it console log 'pass' 5 times and then does nothing when button clicked. but if i uncomment out the closure bit (return), console.log will echo out the i, but not log 'pass'. I did find relevant answer but i don't get why with closure onclick doesn't log the 'pass' string when button clicked instead does log out the i.

How do JavaScript closures work?

解决方案

What you are doing here is directly calling the function clicked instead of setting it as an event handler.

i don't get why with closure onclick doesn't log the 'pass' string when button clicked instead does log out the i.

well, your closure was

return function(){
  console.log(i);
}

Why would that log anything except i ?

The function that creates this closure should log "pass" five times during page initialization (as you call five times in the loop, each time it logs a line and returns the closure).

You could use bind.

nodes[i].addEventListener('click', clicked.bind(nodes[i], i));

This will give you i as a parameter to the function, so that you can do

console.log("pass", i);

这篇关于eventListener中的JavaScript闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆