Variable in wrong scope (maybe needs a closure?)

130 views Asked by At

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?

2

There are 2 answers

0
bjornd On BEST ANSWER

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))
}
0
mrK On

doesn't onclick pass in (sender, eventArgs) allowing you to access this through sender?