Skip to content

Commit 23120b6

Browse files
Avoid a too-common error in assigning event-handlers.
1 parent 0ebe390 commit 23120b6

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

event_handlers_in_loops.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Don' do it this way - you'll more than likely not get what you want!
2+
for (i = 0; i < divs.length; i++) {
3+
div_id = divs[i].id;
4+
divs[i].onclick = function () {
5+
alert(div_id);
6+
};
7+
}
8+
9+
// the function you're declaring in each iteration is closing over the div_id
10+
// variable, not its individual iteration values. Each clicked div will alert
11+
// the final value of div_id that caused the loop to terminate.
12+
//
13+
// Instead, if you want each clicked div to alert its own id, do it like this:
14+
function make_handler(div_id) {
15+
return function() {
16+
alert(div_id);
17+
}
18+
}
19+
20+
for (i = 0; i < divs.length; i++) {
21+
div_id = divs[i].id;
22+
divs[i].onclick = make_handler(div_id);
23+
}

0 commit comments

Comments
 (0)