javascript - 使用“switch”语句显示星期几。(问题)
问题描述
我遇到了显示一周中某一天的 switch 语句的问题。我想从用户那里获取输入(一个数字)并显示一周中的某一天。这是我的源代码,请指出我的功能有什么问题。
let clickButton = document.getElementById("button");
clickButton.addEventListener("click", function weekDay() {
let day = Number(document.getElementById("numberDay").value);
switch (day) {
case 0:
alert("It's Sunday!")
break;
case 1:
alert("It's Monday");
break;
case 2:
alert("It's Tuesday");
break;
case 3:
alert("It's Wednesday");
break;
case 4:
alert("It's Thursday");
break;
case 5:
alert("It's Friday");
break;
case 6:
alert("It's Saturday");
break;
}
})
Enter a number: <input type="text" id="numberDay">
<button id="button">OK</button>
解决方案
你的代码看起来不错。但是,如果用户输入除了 0-6 数字之外的其他内容,您可能需要添加默认情况。也许为 7 号添加另一个案例以用于周日。
switch (day) {
case 0:
case 7:
alert("It's Sunday!")
break;
case 1:
alert("It's Monday");
break;
case 2:
alert("It's Tuesday");
break;
case 3:
alert("It's Wednesday");
break;
case 4:
alert("It's Thursday");
break;
case 5:
alert("It's Friday");
break;
case 6:
alert("It's Saturday");
break;
default:
alert("Wrong input!");
break;
}
不妨将输入类型从更改text
为number
<input type="number" id="numberDay">
或者您是否遇到任何其他问题?
推荐阅读
- c - 如何解决无法正确运行图形 c 程序的代码块
- java - 如何修复exo播放器加载视频慢的问题
- javascript - 我必须点击搜索按钮两次才能从 api 获取数据
- php - Laravel Where 搜索查询
- android - 对 firebase 函数的调用永远不会成功
- python - line.strip() 方法说明
- java - 阅读间接状态与。在java中读取变量的直接状态
- python - 有没有使用 DOI(Rest API 调用)获取 Crossref 元数据的解决方案
- php - 当 WooCommerce 中的产品缺货时更改单个添加到购物车的文本
- javascript - Cordova 黑莓便利键