Just a quick question, can anyone tell me why this doesnt work and how to fix it? Essentially its taking a group of table rows in HTML and dynamically attaching click events to them.
for (var a=index; a<rows.length; a++) {
tr = rows[a];
tr.onclick = function() { DropDownManager.onItemClick(tr, a); };
tr.observe("click", function() { DropDownManager.onItemClick(tr, a); });
}
The problem with this code is that the values passed into DropDownManager.onItemClick are always the last items in the loop, this isn't what im after as i wanted them to be the current value in that stage of the loop. I realize I'm missing something quite simple but cant for the life of me work it out!
JavaScript has no block scope, so e.g. loops don't create a new scope. You can create one by using a function:
for (var a=index; a<rows.length; a++) {
(function(a) {
tr = rows[a];
tr.onclick = function() { DropDownManager.onItemClick(this, a); };
tr.observe("click", function() { DropDownManager.onItemClick(this, a); });
}(a));
}
Depending on what rows
and tr
are, you might not even need the loop index. Maybe you can get the elements index inside the event handler through another way. E.g. if tr
is a HTMLTableRowElement
[MDN], then you can get its position among the other rows via this.rowIndex
.
Btw. why are you binding the same event handler twice?