如何在循环的同时使用if / else语句?

时间:2015-04-21 15:08:49

标签: javascript

我拥有的东西:我有一个盒子,每次点击时都会在红色和蓝色之间不断切换。每次点击该框时,玩家都会得到一个点。

我想要的:当点击该框并且它是红色时,我想要一个点添加到玩家的分数。当它是蓝色并点击时,我想要一条消息出现,说"你输了。"

这是我的代码:

var clickedTime;
var createdTime;
var reactionTime;
var clickable;
var score = 1;

function makeBox() {
    var time = (Math.random() * 3000);
    clickable = false;
    console.log(clickable);
    setTimeout(function () {
        document.getElementById("box").style.backgroundColor = "red";
        clickable = true;
        console.log(clickable);
        createdTime = Date.now();
    }, time);
}

makeBox();

document.getElementById("box").onclick = function () {
    clickedTime = Date.now();
    reactionTime = (clickedTime - createdTime) / 1000;
    document.getElementById("score").innerHTML = score;
    this.style.backgroundColor = "blue";
    makeBox();
    score++
}

我尝试过添加(没有成功,也许我把它放在了错误的位置):

if (clickable=true) {
    makeBox();
    score++
} else {    
    alert("You lose!");
}

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

您的代码中有错误:

而不是调用正在测试布尔值的if(clickable == true),而是调用正在测试赋值的if(clickable = true),这将改变代码的结果:

var clickedTime;
var createdTime;
var reactionTime;
var clickable;
var score = 1;

function makeBox() {
    var time = (Math.random() * 3000);
    clickable = false;
    console.log(clickable);
    setTimeout(function () {
        document.getElementById("box").style.backgroundColor = "red";
        clickable = true;
        console.log(clickable);
        createdTime = Date.now();
    }, time);
}

makeBox();

document.getElementById("box").onclick = function () {
    clickedTime = Date.now();
    reactionTime = (clickedTime - createdTime) / 1000;
    document.getElementById("score").innerHTML = score;
    this.style.backgroundColor = "blue";
        if (clickable==true) {
            makeBox();
            score++
        } else {    
            alert("You lose!");
        }
}