2012-03-11 49 views
3

コードに問題があり、それが私にナットをもたらしています。私はこれに何時間も執着してきました。そして最悪の部分は、それが本当に単純だと仮定していることです。私はそれを理解できません。JavaScript内の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「PREVヶ月でボタンをクリックした場合、私は「次の月」IDでボタンをクリックするたびに、それは常に2です。 "それは常に12です。それは決して変化しません。私は間違って何をしていますか?

答えて

6

スクリプトコードは1回だけ実行されます。クリックした後にクリックハンドラを変更していないので、ハンドラは常に同じ結果を返します。

しかし、ボタンごとに1つのハンドラを使用し、実行時に12個のハンドラを変更するのではなく、次の/前の月を計算するために算術演算を使用する方が簡単です。

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

うん、おかげで。私は今は固定されていますが、私は特に「+ 10」が好きではありません。 10はどこからも出現しそうな "魔法の数"です。おそらく、Neysorの答えのように、より明示的にコードを書くことがベストでしょう。 –

+0

個人的には、(暗黙の)グローバルスコープではなく、変数に1つのハンドラとクロージャスコープを使用します。外部で使用する必要がある場合は、 '$(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/

関連する問題