To be completely honest when i looked at this example without running the code i was thinking of the problem that often comes up with you use a for loop with an addEvent and alert the index, i wasn't thinking about the each, who's closure is supposed to take care of the wonkiness i was solving unnecessarily.

In any event... index should be defined in your original code.


On Mar 4, 2009, at 11:33 PM, Tom Occhino wrote:

This is like a 300 level JavaScript lesson right here...

document.getElements('img').each(function(img, index){
        img.addEvent('click', function(index) {
                alert(index + 1);
        }.bind(this, index));
});

// or

document.getElements('img').each(function(img, index){
        img.addEvent('click', function(index) {
                alert(index + 1);
        }.pass(index));
});

I will leave it as an exercise to the reader to figure out why your code is wrong, and this code is right ;)

- tom


On Mar 2, 2009, at 6:52 PM, Matt Thomson wrote:


Hi does anyone know how I would do this:

html:

<div id="img_holder">
 <img src="img1.gif" />
 <img src="img2.gif" />
 <img src="img3.gif" />
</div>

javascript:

this.imageArray = $('img_holder').getElements('img');

this.imageArray.each(function(el,index)
{
  el.addEvent('click', function()
  {
      alert(index + 1);
      //if image 1 is clicked I want it to alert "1"
     //if image 2 is clicked I want it to alert "2"
     //presently index is undefined
   });
});

Thanks,

Matt.


Reply via email to