I’m writing a simple calculator in JavaScript. I have buttons for 0 to 9, +, -, *, /, =, and C for clear. I want to assign event handlers to each button’s onclick. Since the buttons for 0 to 9 have very similar event handlers, I used a for loop to assign to each button’s onclick:
/* one, two, three, etc. are variables defined earlier.
*
* for example,
* var one = document.getElementById("one");
* where that element is a button that says "1"
*
* the "display" element is the calculator display
*/
var num_array = [one, two, three, four, five,
six, seven, eight, nine, zero];
for (var i = 0; i < num_array.length; ++i) {
num_array[i].onclick = function() {
document.getElementById("display").value += num_array[i].value;
};
}
But this doesn’t work, because onclick’s event handler is dependent on i, which will always be 10 once the for loop is finished. Is there any way to remove that dependency on i, while also keeping my code succinct (i.e. using a for loop)? I don’t want to write out event handlers for each individual button.
Why not just use
thisin place ofnum_array[i]?thiswill point to the element that was clicked.