为什么我的if语句没有返回预期的结果?

时间:2017-07-22 12:22:13

标签: javascript if-statement

我正在尝试制作一个Catchphrase风格的游戏,用户逐渐点击覆盖图片的方块,直到他们可以猜到图片中的人。相关代码和评论如下:

//页面刷新时显示的三个随机图像之一。

        var randomImage = new Array();
        randomImage[0] = "/IMAGES/0.jpg"
        randomImage[1] = "/IMAGES/1.jpg"
        randomImage[2] = "/IMAGES/2.jpg"

        var randomNumber = Math.random();

        randomNumber = randomNumber * randomImage.length;

        randomNumber = Math.round(randomNumber);

        if (randomNumber == 0) {

            document.getElementById("backPic").src="../IMAGES/0.jpg";

        }

        else if (randomNumber == 1)  {

            document.getElementById("backPic").src="../IMAGES/1.jpg";

        }

        else {

            document.getElementById("backPic").src="../IMAGES/2.jpg";

        }

//当用户提交他们的答案时,如果他们是正确的,他们会收到警告'干得好!'

        document.getElementById("submitGuess").onclick = function() {

            var correctAnswer0 = "Terry";

            var correctAnswer1 = "Drogba";

            var correctAnswer2 = "Lampard";

            if (document.getElementById("userGuess").value == correctAnswer1 && randomNumber == 1){


                    alert("Well done!");


            }

        }

在上面的if语句中,我希望只有当点击提交,并且userGuess正确并且randomNumber等于1时,才会提示用户“完成”。但是,当显示不同的图片时单击提交按钮(即randomImage [2])时,它会将图片更改为randomImage [1]。

任何人都可以帮助我并告诉我为什么这不起作用吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

按钮提交表单,以便重新加载页面。要避免这种情况,请将事件参数添加到您的点击处理函数(例如,将其命名为e)并执行:

e.preventDefault();

这将取消表单提交,因此不会重新加载页面。

请注意,通过使用更好的数据结构,您的代码可以大量减少:



// One of three random images to be displayed when page refreshes.
var persons = [
    {name: "Terry", img: "https://upload.wikimedia.org/wikipedia/commons/f/f8/John_Terry_during_a_match_vs_Everton_at_Stamford_Bridge_in_2006.jpg"},
    {name: "Drogba", img: "https://upload.wikimedia.org/wikipedia/commons/thumb/8/89/Didier_Drogba_9248.JPG/399px-Didier_Drogba_9248.JPG"},
    {name: "Lampard", img: "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b3/Frank_Lampard%2713-14.JPG/399px-Frank_Lampard%2713-14.JPG"}
];
var randomNumber = Math.floor(Math.random() * persons.length);
backPic.src = persons[randomNumber].img;

// When user submits their answer, if they are correct, they are alerted 'Well done!'
submitGuess.addEventListener("click", function(e) {
    alert(userGuess.value == persons[randomNumber].name 
            ? "Well done!"
            : "Try again"
    );
    e.preventDefault(); // cancel form submission.
});

<form>
<img id="backPic" width="20%" height="20%"><br>
Guess:<input id="userGuess">
<button id="submitGuess">Guess</button>
</form>
&#13;
&#13;
&#13;