简体   繁体   English

尝试在以下函数中未成功重新分配全局变量(javascript)

[英]Trying to reassign a global variable within a following function unsuccessfully (javascript)

I'm trying to make a basic weather site and I want the user to be able to input the number of days they want displayed. 我正在尝试建立一个基本的天气站点,希望用户能够输入他们想要显示的天数。 I created a global variable that would hold the number that that user entered. 我创建了一个全局变量,该变量将保存用户输入的数字。 The user clicks submit and the function is called to reassign that variable to the desired number of days. 用户单击提交,然后调用该函数以将该变量重新分配给所需的天数。 I've checked using console for the value of this variable within the function in charge of reassigning it and it works but when I check the console just outside the function the variable reverts back to its previous value 我已经在控制台中使用控制台检查了该变量的值以负责重新分配它,并且它可以正常工作,但是当我在函数外部检查控制台时,该变量又恢复为先前的值

 <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); 

the html HTML

 <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> 

Try following code if you want to keep max day as 5 you can put max = "5" as I placed min = "0" 如果您希望将最大天数保持为5,请尝试以下代码,可以将max =“ 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM