Bill0123
2015-08-14 10:03
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>switch</title> <script type="text/JavaScript"> function day(){ var myweek =prompt("what day is it today?","1"); switch(myweek) { case 1: case 2: document.write("学习理念知识"); break; case 3: case 4: document.write("到企业实践"); break; case 5: document.write("总结经验"); break; case 6: case 7: document.write("周六、日休息和娱乐"); break; default:alert("input error!");} } </script> </head> <body> <input type="button" value="click here!" onClick="day()"> </body> </html>
这里接收到的值是字符串,下面匹配的却是整型,2种解决方法。
一,直接把接收到的值强制转换为数字类型,如:
var myweek =parseInt(prompt("what day is it today?","1"));
二,把下面所有case语句后面的值改为字符串,即加引号,如:
switch(myweek) { case "1": case "2": document.write("学习理念知识"); break; case "3": case "4": document.write("到企业实践"); break; case "5": document.write("总结经验"); break; case "6": case "7": document.write("周六、日休息和娱乐"); break; default:alert("input error!");} }
switch(parseInt(myweek))
这样也可以
var myweek =prompt("what day is it today?","1");
你的myweek获取到的是一个字符串,把所有case都改成字符串
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>switch</title> <script type="text/JavaScript"> function day(){ var myweek =prompt("what day is it today?","1"); switch(myweek) { case "1": case "2": document.write("学习理念知识"); break; case "3": case "4": document.write("到企业实践"); break; case "5": document.write("总结经验"); break; case "6": case "7": document.write("周六、日休息和娱乐"); break; default:alert("input error!");} } </script> </head> <body> <input type="button" value="click here!" onClick="day()"></body> </html>
JavaScript进阶篇
468194 学习 · 21891 问题
相似问题
回答 3