尝试在以下函数中重新分配全局变量失败(javascript)

时间:2017-10-28 15:45:37

标签: javascript global-variables

我试图创建一个基本的天气网站,我希望用户能够输入他们想要显示的天数。我创建了一个全局变量,用于保存用户输入的数字。用户单击“提交”并调用该函数以将该变量重新分配给所需的天数。我已经在负责重新分配它的函数中使用控制台检查了这个变量的值,但是当它在函数外检查控制台时,变量恢复到之前的值



<script>
           
           var days
            var table = ""
            
           
           function checkValue(){
    var day = document.getElementById("day").value;
    if (day == 1){
        days = 1;
    }
    else if (day == 2){
        days = 2;
    }
    else if (day == 3){
        days = 3;
    }
    else if (day == 4){
        days = 4;
    }
    else if (day == 5){
        days = 5;
    }
    else{
        alert("Please enter a number (1-5)");
    }
}
         
          console.log(days);
&#13;
&#13;
&#13;

html

&#13;
&#13;
<div class = "main">Please enter the day of the week for which you would like the forcast the be displayed (1-5)</div>
        <br>
        <div class="main">
            Enter day here:<br>
            <input id = "day" type = "text" name = "day" value=""><br>
            <br>
            <button id = "submit" name ="button" onClick = "checkValue();" value="submit">Submit</button>
        </div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

如果您想将最大日期保持为5,请尝试以下代码,因为我放置了min =“0”

(function() {
    var day = document.getElementById("day").value;
    document.getElementById("btn").onclick = function() {
      myNode()
    };
    
   // alert(day);
    
    function myNode(){
    var day = document.getElementById("day").value;
    console.log(day);
    if (day == 1){
        day == 1;
    }
    else if (day == 2){
        day == 2;
    }
    else if (day == 3){
        day == 3;
    }
    else if (day == 4){
        day == 4;
    }
    else if (day == 5){
        day == 5;
    }
    else{
        alert("Please enter a number (1-5)");
    }

 



}

})();
<input type="number" id="day" min="1">
<button id="btn">Click</button>