0

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?

Devin Rhode
  • 23,026
  • 8
  • 58
  • 72

2 Answers2

3

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))
}
bjornd
  • 22,397
  • 4
  • 57
  • 73
0

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

mrK
  • 2,208
  • 4
  • 32
  • 46