Javascript Switch无法正常工作,我不确定原因

时间:2015-12-12 09:49:12

标签: javascript html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8"/>
        <title> Javascript - switch statements</title>
        <script type="text/javascript">

        var car="ford";

        switch(car){
            case "ferrari";
                document.write("Italian Stalion hey?");
                break;
            case "porsche";
                document.write("German Precision, I like that!");
                break;
            case "dodge";
                document.write("American cars can't corner properly");
                break;

            default:
                document.write("I don't know that car"); 
            //no need for a break because this is the end, its going to end anyways that would be redundant
        }
        </script>
    </head>
    <body>
    </body>
    </html>

我没有看到任何错误。无论我是否将变量更改为保时捷或福特,为什么没有任何回报。默认类搞砸了这个???

2 个答案:

答案 0 :(得分:0)

只需更换案例&#34;陈述&#34 ;; with case&#34; statement&#34;:

您只是立即用分号终止案例陈述。

<强> Here is a fiddle.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title> Javascript - switch statements</title>
<script type="text/javascript">
var car="ford";
switch(car){
   case "ferrari": //This line has changed
       document.write("Italian Stalion hey?");
       break;
   case "porsche": //This line has changed
       document.write("German Precision, I like that!");
       break;
   case "dodge": //This line has changed
       document.write("American cars can't corner properly");
       break;
   default:
       document.write("I don't know that car");
}
</script>
</head>
<body>
</body>
</html>

答案 1 :(得分:0)

在case语句结束时,使用冒号(:)而不是分号(;)。那么你的代码应如下所示。

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Javascript - switch statements</title>
    <script>
        var car = "ford";

        switch (car){
            case "ferrari":
                document.write("Italian Stalion hey?");
                break;
            case "porsche":
                document.write("German Precision, I like that!");
                break;
            case "dodge":
                document.write("American cars can't corner properly");
                break;
            default:
                document.write("I don't know that car");
                break;
        }
    </script>
</head>
<body>

</body>
</html>