문제

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?

도움이 되었습니까?

해결책

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))
}

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top