We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 0ebe390 commit 23120b6Copy full SHA for 23120b6
event_handlers_in_loops.js
@@ -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
17
+ }
18
19
20
21
22
+ divs[i].onclick = make_handler(div_id);
23
0 commit comments