As Ionut G. Stan says, the issue is the closure over 'i'. RaYell is right about your wanting to declare the var (but not about that solving the problem).
That loop also repeatedly re-executes the $$
call, which isn't really ideal, and completely unnecessarily calls $
to look up elements you've already looked up (via $$
).
FWIW:
Event.observe(window, 'load', function() {
$$('ul#review_list li').each(function(elm, index) {
++index; // Now it's 1-based
elm.observe('click', function(event) {
alert(index);
});
});
});
$$
looks up the elements, Enumerable#each
then iterates through the result calling the given function with the element reference and its zero-based index in the array. The event handler is then a closure over several things, including the index
parameter passed into the #each
iterator.
*Edit: I'm sorry, I just realized I made a massive assumption below: That the cover_x elements are, in fact, the list items under review_list. If they're not, disregard the below and my apologies! - T.J.*
So that works, but it's also unnecessarily complex. Event delegation could be your friend here: Look for clicks on the list, rather than list items:
Event.observe(window, 'load', function() {
$('review_list').observe('click', function(event) {
var li;
li = event.findElement('li');
if (li) {
// ...your code here to interact with the list item.
// If you need the index, you can find it easily enough:
// index = parseInt(li.id.substring(6));
// ...since your IDs on the LI items is "cover_x" with x
// being the index.
}
});
});