多个变量和提示

时间:2016-01-29 22:44:17

标签: javascript image variables var prompt

所以基本上我需要在回答问题后使用JavaScript和变量将我的网站从一个图像转换到另一个图像。我会提示用户关于那里的心情从1-10他们选择1-3(悲伤)如果他们选择4-7(中性)图像变为悲伤的脸,如果他们选择8-图像变为中性脸10(开心)网站上的图片会变成幸福的脸。我的代码虽然不起作用我已经尝试了所有的东西

    <head>
    <title>Mood</title>
    <meta charset="UTF-8">
    <script>          
        var sad = 1 , sad2 = 2, sad3 = 3; 
        var n1 = 4, n2 = 5, n3 = 6, n4 = 7;
        var h1 = 8, h2 = 9, h3 = 10;  

        var x = prompt("What is your mood from 1-10? 1 being sad, 10 being Happy.","What is your mood?"); 
            if(x === sad || x === sad2 || x === sad3){
                document.getElementByTagName("img").src = "sad.png";
                document.getElementById("msg").innerHTML = "Sad.";
                document.getElementById("msg").href = "http://www.sad.com";
            }
            else if(x === n1 || x === n2 || x === n3 || x === n4){
                document.getElementByTagName("img").src = "neutral.png";
                document.getElementById("msg").innerHTML = "Neutral.";
                document.getElementById("msg").href = "http://www.neutral.com";
            }
            else if(x === h1 || x === h2 || x === h3){
                document.getElementByTagName("img").src = "happy.png";
                document.getElementById("msg").innerHTML = "Happy.";
                document.getElementById("msg").href = "http://www.happy.com";
            }
    </script>
</head>
<body style="text-align:center">
    <img src="neutral.png">
    <h1><a id="msg" href="">Waiting...</a></h1>
</body>

我的编码中没有任何错误我正在使用NetBeans,但是我在提示中输入的任何数字都是空白的。

2 个答案:

答案 0 :(得分:3)

问题似乎是===运营商。它检查绝对相等而不进行类型转换。

当你在提示符中输入1时,它很可能记录为&#34; 1&#34;,即一个字符串。当您检查是否x === sad时,您是否正在检查&#34; 1&#34;等于1(它没有 - 第一个是字符串,第二个是数字)。

要解决此问题,请使用较弱的==运算符(将适当地转换类型),或者不是将1分配给var sad,而是指定"1"。< / p>

答案 1 :(得分:1)

prompt()返回一个String。如果要使用===,则应将其与其他字符串进行比较。请参阅此问题Does it matter which equals operator (== vs ===) I use in JavaScript comparisons?

制作所有比较器变量字符串:

// Make Strings
var sad = "1",
    sad2 = "2",
    sad3 = "3";
var n1 = "4",
    n2 = "5",
    n3 = "6",
    n4 = "7";
var h1 = "8",
    h2 = "9",
    h3 = "10";
//

var x = prompt("What is your mood from 1-10? 1 being sad, 10 being Happy.", "What is your mood?");
if (x === sad || x === sad2 || x === sad3) {
    document.getElementByTagName("img").src = "/img/ico/favicon.png";
    document.getElementById("msg").innerHTML = "Sad.";
    document.getElementById("msg").href = "http://www.sad.com";
} else if (x === n1 || x === n2 || x === n3 || x === n4) {
    document.getElementByTagName("img").src = "/img/ico/favicon.png";
    document.getElementById("msg").innerHTML = "Neutral.";
    document.getElementById("msg").href = "http://www.neutral.com";
} else if (x === h1 || x === h2 || x === h3) {
    document.getElementByTagName("img").src = "/img/ico/favicon.png";
    document.getElementById("msg").innerHTML = "Happy.";
    document.getElementById("msg").href = "http://www.happy.com";
}