0
나는 JavaScript로 간단한 계산기를 작성하고있다. 0, 9, +, -, *, /, = 및 C의 버튼이 있습니다. 각 단추의 onclick에 이벤트 처리기를 할당하려고합니다. 온 클릭의 이벤트 핸들러가있는 것입니다, 난에 의존하기 때문에,onclick은 for 루프의 i 값에 종속됩니다. 어떻게 제거합니까?
/* 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;
};
}
하지만이 작동하지 않습니다 : 0에서 9까지의 버튼과 매우 유사 이벤트 핸들러를 가지고 있기 때문에, 나는 각 버튼의 OnClick에 할당 for 루프를 사용 for 루프가 끝나면 항상 10이됩니다. 그 코드에 대한 의존성을 없애고, 코드를 간결하게 유지할 수있는 방법이 있습니까 (예 : for 루프 사용)? 개별 버튼마다 이벤트 핸들러를 작성하고 싶지 않습니다.