Search code examples
javascriptclosureslexical-closures

Variable in wrong scope (maybe needs a closure?)


I have the following code that is in need of a closure:

var numItems = document.getElementsByClassName('l').length;
for (var i = 0; i < numItems; i++) {
  document.getElementsByClassName('l')[i].onclick = function (e){
    preview(this.href, i);
  };
}

What happens is that whenever an item is clicked, preview always the same number for i

I suspect what I need to do is

function indexClosure(i) {
  return function(e) {
    preview(this.href, i);
  }
}

And assign the onclick's like this:

document.getElementsByClassName('l')[i].onclick = indexClosure(i);

But then this would no longer refer to my link... how is this problem solved?


Solution

  • Use closure to capture the counter of the cycle:

    var numItems = document.getElementsByClassName('l').length;
    for (var i = 0; i < numItems; i++) {
      (function(i){
        document.getElementsByClassName('l')[i].onclick = function (e){
          preview(this.href, i);
        };
      }(i))
    }