Let's say I have a series of links on the page: <a id="link0"
href="#">Link 0</a><a id="link1" href="#">Link 1</a><a id="link2"
href="#">Link 2</a><a id="link3" href="#">Link 3</a><a id="link4"
href="#">Link 4</a> and so forth.

I want to attach event handlers to each of them using a for loop for
simplicity sake. I can't just do:

for (var i = 0; i < 5; i++) {
   $("#link" + i).click(function(event) {
      alert(i);
      event.preventDefault();
   });
}

because that will just alert 5 on each link since "i" is being
remembered at the last value of the for loop when the handlers are
actually called. To get around this, I used the common approach of
calling a function that passes "i" and returns a function that does
what I want.

for (var i = 0; i < 5; i++) {
   $("#link" + i).click(createEventHandler(event, i));
}

function createEventHandler(event, i) {
   alert(i);
   event.preventDefault();
}

This works just fine in Internet Explorer and Safari, but it breaks
the page in Firefox because Firefox says the event is not defined.

Is there something wrong my code or my approach? I think I'm doing it
right. If it worked only in IE, I'd be a bit more concerned about my
code, but because it works in Safari I tend to think it's an issue
with Firefox or the jQuery code itself.

Reply via email to