2012-03-11 2 views
3

코드 조각에 문제가있어 견과류가되었습니다. 나는 이것을 몇 시간 동안 붙들어 왔으며, 최악의 부분은 그것이 정말로 간단하다고 가정하고 있다는 것입니다. 나는 그것을 이해할 수 없다.자바 스크립트에서 if 문 내의 변수 값을 변경하십시오.

Javascript/jQuery를 사용하여 간단한 이벤트 캘린더를 만들려고합니다. 이제

var currentMonth = 1; 
if (currentMonth == 1) { 
    $("#prev-month").click(function() { 
     currentMonth = 12; 
    }); 
    $("#next-month").click(function() { 
     currentMonth = 2; 
    }); 
} 
if (currentMonth == 2) { 
    $("#prev-month").click(function() { 
     currentMonth = 1; 
    }); 
    $("#next-month").click(function() { 
     currentMonth = 3; 
    }); 
} 
if (currentMonth == 3) { 
    $("#prev-month").click(function() { 
     currentMonth = 2; 
    }); 
    $("#next-month").click(function() { 
     currentMonth = 4; 
    }); 
} 
if (currentMonth == 4) { 
    $("#prev-month").click(function() { 
     currentMonth = 3; 
    }); 
    $("#next-month").click(function() { 
     currentMonth = 5; 
    }); 
} 

이 때마다 내가 ID "다음 달"로 버튼을 클릭 내가 ID를 가진 버튼을 클릭하면, 항상 2입니다 "이전 개월이 내가 가진 그 단순화 된 코드입니다 ", 항상 12입니다. 결코 바뀌지 않습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

답변

6

스크립트 코드는 한 번만 실행됩니다. 클릭 핸들러를 클릭 한 후에는 클릭 핸들러를 변경하지 않으므로 해당 핸들러는 항상 동일한 결과를 제공합니다.

하지만 각 단추에 대해 단일 처리기를 사용하고 런타임에 변경하는 12 개의 처리기 대신에 산술을 사용하여 다음/이전 달을 계산하는 것이 더 간단 할 것이라고 수정하는 대신.

$("#prev-month").click(function() { 
    currentMonth = (currentMonth - 1) || 12; 
}); 
$("#next-month").click(function() { 
    currentMonth = currentMonth % 12 + 1; 
}); 
+0

네, 감사합니다. 이제는 '+ 10'이 맘에 들지 않지만, 이제는 고정되어 있습니다. 10은 아무데도 등장하지 않는 것 같은 "매직 넘버"입니다. 아마도 Neysor의 대답처럼 코드를 더 명확하게 작성하는 것이 가장 좋습니다. –

+0

개인적으로, (함축 된) 전역 범위 대신 변수에 대해 하나의 핸들러와 클로저 범위를 사용합니다. 외부에서 사용해야 할 경우'$ (this) .parent(). data ('data-current-month', currentMonth)'. –

+0

매직 넘버 대신'(currentMonth - 1) % 12 || 12;' –

3

.click() 기능을 잘못 사용하고 있습니다. 이처럼해야한다 :

var currentMonth = 1; 

$("#prev-month").click(function() { 
    currentMonth--; 
    if (currentMonth == 0) { 
     currentMonth = 12; 
    } 
} 
$("#next-month").click(function() { 
    currentMonth++ 
    if (currentMonth == 13) { 
     currentMonth = 1; 
    } 
});​ 
+0

이 코드를 사용해 주셔서 감사합니다. 내가 함수 안에 문장을 넣어야한다는 것을 몰랐다. –

0

당신은 당신의 참조 및 ($(this).is()를 사용하여) 하나의 클릭 핸들러를 저장하기 위해 클로저를 사용할 수 있습니다

<div> 
    Current Month: <input type="text" id="current-month"/> 
    <button id="prev-month">Previous Month</button> 
    <button id="next-month">Next Month</button> 
</div> 

$(document).ready(function(){ 
    var currentMonth = 1, 
     $currentmonth = $('#current-month'); 

    $currentmonth.val(currentMonth); 

    $("#prev-month, #next-month").click(function() { 
     var $this = $(this); 

     if ($this.is('#prev-month')) { 
      currentMonth = currentMonth - 1; 
     } else { 
      currentMonth = currentMonth + 1; 
     } 

     if (currentMonth == 0) { 
      currentMonth = 12; 
     } else if (currentMonth > 12) { 
      currentMonth = 1; 
     } 

     $currentmonth.val(currentMonth); 

     console.log('Current Month: ' + currentMonth); 
    }); 
}); 

http://jsfiddle.net/pCs2G/

관련 문제