eventListener中的JavaScript闭包 [英] JavaScript closure within eventlistener
问题描述
< 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 。 >
你在这里做的是直接调用函数 当按钮被点击时,close onclick不会记录'pass'字符串,而是注销i。 / p> 为什么除了 创建此闭包的函数应在页面初始化期间记录pass五次(因为在循环中调用五次, 您可以使用 这将给你 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 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 Why would that log anything except 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 This will give you
这篇关于eventListener中的JavaScript闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! clicked
而不是将其设置为事件处理程序。
return function(){
console.log(i);
}
i
?
$ 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>
clicked
instead of setting it as an event handler.
return function(){
console.log(i);
}
i
?bind
.nodes[i].addEventListener('click', clicked.bind(nodes[i], i));
i
as a parameter to the function, so that you can doconsole.log("pass", i);