为什么这个简单的代码不起作用?

时间:2013-04-15 00:56:37

标签: javascript

我有一个简单的js无法工作

我需要为每个var显示相应的vaule,即玩具故事3显示Comedy出色的选择等等

问题似乎在于if else语法

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>help</title>
</head>

<body>
<script type="text/javascript">

var movie = prompt("Select your favorite movie").toLowerCase();

if(movie =="toy story 3","kung fu Panda","RIO");
{
document.write("<p>Comedy splendid choice</p>")
}
else if(movie ="sex in the city","the backup plan","twilight");
{
document.write("<p>Chick flicks are always fun</p>")
}
else if(movie ="fast 5" || movie=="the karate kid");
{
document.write("<p>Action is satisfaction/p>")
}
else
{
document.write("<p>I’m sure it’s a good movie I just don’t know about it/p>")
}

</script>
</body>
</html>

4 个答案:

答案 0 :(得分:2)

首先,在结尾;语句中删除if else

其次,使用||创建或逻辑表达。

第三,你的输入是小写的,所以也要将movie与小写字面值进行比较。

第四,在比较相等时使用===用于变量赋值

试试这个:

var movie = prompt("Select your favorite movie").toLowerCase();

if(movie =="toy story 3" || movie == "kung fu panda" || movie=="rio")
{
   document.write("<p>Comedy splendid choice</p>");
}
else if(movie =="sex in the city" || movie == "the backup plan" || movie == "twilight")
{
   document.write("<p>Chick flicks are always fun</p>");
}
else if(movie =="fast 5" || movie=="the karate kid")
{
   document.write("<p>Action is satisfaction/p>");
}
else
{
   document.write("<p>I’m sure it’s a good movie I just don’t know about it/p>");
}

答案 1 :(得分:0)

您需要创建一个或:

if(movie =="toy story 3" || movie == "kung fu Panda" || movie == "RIO")
{
document.write("<p>Comedy splendid choice</p>")
}
.
.
.

答案 2 :(得分:0)

“不工作”是什么意思?你能详细说明吗?

如果您的意思没有显示,请检查您的代码:

<script type="text/javascript">
    var movie = prompt("Select your favorite movie").toLowerCase();

    if(movie =="toy story 3","kung fu Panda","RIO")
    {
        document.write("<p>Comedy splendid choice</p>");
    }
    else if(movie ="sex in the city","the backup plan","twilight")
    {
        document.write("<p>Chick flicks are always fun</p>");
    }
    else if(movie ="fast 5" || movie=="the karate kid")
    {
        document.write("<p>Action is satisfaction/p>");
    }
    else
    {
        document.write("<p>I’m sure it’s a good movie I just don’t know about it/p>");
    }
</script>

你错过了分号(;)。你应该在声明的末尾放置分号,而不是在大小写之后。

应该是:

if ( condition == true) 
{
    document.write("Hey, it's true!");
}

NOT:

if ( condition == true); // Semi-colon here means, it's the end of the statement
                         // the code after won't be executed
{
    document.write("Hey, it's true!"); // Semi-colon should be here
}

答案 3 :(得分:-1)

使用switch语句而不是多个if if elses ...

switch(movie)
{
    case "Toy story":
        document.write("<p>Comedy splendid choice</p>");
        break;

    case "fast 5":
        document.write("<p>Action is satisfaction/p>");
        break;
}
相关问题