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); // } } (var = 0; < nodes.length; i++) { nodes[i].addeventlistener('click', clicked(i)); } </script>
i try have understanding on js closure, above function add listener buttons. console log 'pass' 5 times , nothing when button clicked. if uncomment out closure bit (return), console.log echo out i, not log 'pass'. did find relevant answer don't why closure onclick doesn't log 'pass' string when button clicked instead log out i.
what doing here directly calling function clicked
instead of setting event handler.
i don't why closure onclick doesn't log 'pass' string when button clicked instead log out i.
well, closure was
return function(){ console.log(i); }
why log except i
?
the function creates closure should log "pass" 5 times during page initialization (as call 5 times in loop, each time logs line , returns closure).
you use bind
.
nodes[i].addeventlistener('click', clicked.bind(nodes[i], i));
this give i
parameter function, can do
console.log("pass", i);
Comments
Post a Comment