2014-02-11 81 views
0

我想用If If else語句在警報中調用一個變量。Javascript If then else statement

我在頁面加載時創建全局變量currentmonth。我測試了一個值正在加載到當前月份,它正在工作。

我也在頁面加載時創建全局變量(datejanuary到datedecember)。我也測試了這些值,他們正在工作。

基本上我想要做的是獲取當前月份並將其與數組中的值進行比較,並在警報中顯示消息。例如,1月份的消息是「迷你高爾夫 - 高爾夫可能是迷你的,競爭將會很大,贏家可以獲得戰利品!」 2月的消息將是「遠足 - 這不是關於目的地,而是關於旅程。」

下面是我爲此創建的功能,我無法讓它工作。我錯過了什麼?

<script> 
    function dateMonth() 
    { 
    var currentdate = ""; 
    if (currentmonth == "January") 
    { 
    currentdate = datejanuary; 
    } 
    else if (currentmonth == "February") 
    { 
    currentdate = datefebruary; 
    } 
    else if (currentmonth == "March") 
    { 
    currentdate = datemarch; 
    } 
    else if (currentmonth == "April") 
    { 
    currentdate = dateapril; 
    } 
    else if (currentmonth == "May") 
    { 
    currentdate = datemay; 
    } 
    else if (currentmonth == "June") 
    { 
    currentdate = datejune; 
    } 
    else if (currentmonth == "July") 
    { 
    currentdate = datejuly; 
    } 
    else if (currentmonth == "August") 
    { 
     currentdate = dateaugust; 
     } 
     else if (currentmonth == "September") 
    { 
    currentdate = dateseptember; 
     } 
     else if (currentmonth == "October") 
     { 
     currentdate = dateoctober; 
     } 
     else if (currentmonth == "November") 
     { 
     currentdate = datenovember; 
     } 
     else 
     { 
     currentdate = datedecember; 
     } 
     { 
     vex.dialog.alert(currentdate); 
     } 
     </script> 

回答

4

如何簡單:

var messages = [ 
    "Mini Golf – the golf may be mini, the competition will be big. To the winner go the ..", 
    "Hike – it’s not about the destination, it’s about the journey.", 
    "..." 
]; 

alert(messages[new Date().getMonth()]); 

getMonth() == 0爲一月)

+1

這是輝煌!奇蹟般有效。非常感謝。我的前額因爲撞到我的顯示器而被撞傷了! – user3087383

0

左右,如果你真的需要做的,如果和別的

<script> 
    function dateMonth() 
    { 
     var currentdate = ""; 
     var currentmonth = new Date().getMonth() 
     if (currentmonth == 1) 
     { 
      currentdate = datejanuary; //Your text 
     } 
     else if (currentmonth == 2) 
     { 
      currentdate = datefebruary; 
     } 
     else if (currentmonth == 3) 
     { 
      currentdate = datemarch; 
     } 
     else if (currentmonth == 4) 
     { 
      currentdate = dateapril; 
     } 
     else if (currentmonth == 5) 
     { 
      currentdate = datemay; 
     } 
     else if (currentmonth == 6) 
     { 
      currentdate = datejune; 
     } 
     else if (currentmonth == 7) 
     { 
      currentdate = datejuly; 
     } 
     else if (currentmonth == 8) 
     { 
      currentdate = dateaugust; 
     } 
     else if (currentmonth == 9) 
     { 
      currentdate = dateseptember; 
     } 
     else if (currentmonth == 10) 
     { 
      currentdate = dateoctober; 
     } 
     else if (currentmonth == 11 
     { 
      currentdate = datenovember; 
     } 
     else 
     { 
      currentdate = datedecember; 
     } 
     vex.dialog.alert(currentdate); 
    } 
</script>