Javascript - if语句错误

时间:2016-08-18 18:47:53

标签: javascript

想知道是否有人可以引导我走向正确的方向,我试图使用Javascript制作一个小游戏来帮助我学习。基本上我声明我想要在我的函数之外更改的所有变量,所以它们行为全局,在代码中工作,但if语句似乎没有证明成功,我似乎无法纠正这个,因为教程指向我的代码是正确的,请参阅下面的代码;

var Refresh;
Refresh = "InActive";

var Counter;
Counter = 0;

var StartTime;


function StartGame() {
    var StartDate;
    StartDate = new Date();
    StartTime = d.getTime();
    Refresh = "Active";
}


function FunctionB1() {
    if (Refresh == "Active"){
        document.getElementById("Bean1").style.display = "None";
        Counter ++;
        document.getElementById("BeanCount").innerHTML = Counter + " Out of 150";
    }
}

3 个答案:

答案 0 :(得分:0)

您需要将d.getTime();更改为StartDate.getTime();以反映变量名称的变化。

function StartGame() {
StartTime = new Date().getTime();
Refresh = "Active";
}

JSFiddle:Solution

编辑包括Xufox的改进。

答案 1 :(得分:0)

尝试从Refresh函数返回变量StartGame()。 它看起来像这样:

function StartGame() {
    var StartDate;
    StartDate = new Date();
    StartTime = d.getTime();
    Refresh = "Active";
    return Refresh;
}

function FunctionB1() {
    var startRefresh = StartGame();
    if (startRefresh == "Active"){
        document.getElementById("Bean1").style.display = "None";
        Counter ++;
        document.getElementById("BeanCount").innerHTML = Counter + " Out of 150";
    }
}

FunctionB1(); // Call the function

答案 2 :(得分:0)

调用StartGame()后,

刷新变量即可访问。您无法在FunctionB1中访问Refresh变量,因为它尚未声明。 试试这个

function StartGame() {
    Refresh = "Active";
}

function FunctionB1() {
    if (Refresh == "Active"){
        console.log('done');
    }
}

function Game() {
    StartGame()
    FunctionB1()
    console.log(Refresh) // Active
};