Q:

Get iterator index into a onmousedown function

I am trying to do a seemingly trivial thing, but I cant figure this out.  I am iterating over items found by the document.getElementByClassName method.  I am doing so with indices so I can keep track of some stuff, and I need that index inside the onmousedown events for that specific element, however I can't figure out to do so. 
var items = document.getElementsByClassName("someClass");

    for (var i = items.length - 1; i >= 0; i--)
    {
        items[i].onmousedown=function(){
            //This does not work:
            var index = i; //I need the i variable from the loop above in here. 
            console.log(index);
            this.innerHTML = doSomeWorkWith(index);
        };  

    }

Anyone know how to do this?  I have thought of adding it to the element itself so I can access a variable there, but I would prefere not to as it would clutter the html code. 

A:

You'll need to create the handler functions on the fly, using another function.  That can easily be done using immediately invoced function expressions (IIFEs).  That way, you'll get the i to be evaluated when defining the handler, not when executing it. 
var items = document.getElementsByClassName("someClass");
for (var i = items.length - 1; i >= 0; i--) {
    items[i].onmousedown = (function (index) {
        return function () {
            console.log(index);
            this.innerHTML = doSomeWorkWith(index);
        }
    })(i);
}

Basically, I'm not directly assigning a function to onmousedown, but creating one on the fly that has the value of i hardcoded. 
To create that handler function, I'm using another function, that I immediately (in-place) invoke after defining it, without ever assigning a name. ( Of course I just could create that function in global scope and us it here, but as I don't need it anywhere else, why should I?) 
[Edit]: To use the event inside that function, use
var items = document.getElementsByClassName("someClass");
for (var i = items.length - 1; i >= 0; i--) {
    items[i].onmousedown = (function (index) {
        return function (event) {
            this.innerHTML = doSomeWorkWith(index);
            // do something with "event" here
        }
    })(i);
}

