I have a whole bunch of similar list items that I want to attach mousedown() functions to. So what I would like to do is replace this:
$('#controls li[id=d1]').mousedown(function(){
console.log('d1');
});
$('#controls li[id=d2]').mousedown(function(){
console.log('d2');
});
with this:
var loopvar;
for (loopvar = 1; loopvar <= 2; loopvar++) {
$('#controls li[id=d' + loopvar + ']').mousedown(function(){
console.log('d' + loopvar);
});
}
(This is a simplified example - I actually have lots of li's to handle.)
But when I click on an li, I always get d3 on the console. The value of loopvar is 3 when the loop ends, so it looks like that is what is happening. So how can I attach the functions using a loop?