Javascript读取和更改变量

时间:2013-08-20 12:19:17

标签: javascript

好的,我一整夜都试着让这个工作,我是一个完整的javascript新手

var Hunger=8;

var interval = setInterval( increment, 10000);

    function changeImage(a) {
        document.getElementById("img").src=a;
    window.setTimeout(goIdle,20000)
    }
function goIdle() {
    document.getElementById("img").src="idle.gif";

function increment(){
        Hunger = Hunger % 24 + 1;
    if (Hunger >= 24)
    }
    if (Hunger >= 12)
        changeImage("cry.gif")
    }
}

function eat() {
    if (Hunger == 6) {
        changeImage("love.gif");
        var Hunger=0
    }
    else {
        ...
    }
}

当我按下按钮触发它时会发生什么,

    <input type="button" value="Eat" onclick='eat();' /> 

它会改变图像,但饥饿感不会下降

2 个答案:

答案 0 :(得分:2)

您的JavaScript可能会停止工作,因为存在一些语法错误。我添加了标签以使其更易读,并在代码中添加了注释以指出这些错误:

var Hunger = 8,
    interval = setInterval(increment, 10000);

function changeImage(a) {
    document.getElementById("img").src = a;
    window.setTimeout(goIdle, 20000)
}

// So far so good, but here it begins..
function goIdle() {
    document.getElementById("img").src = "idle.gif";

    function increment() {
        Hunger = Hunger % 24 + 1;
        // Why is this if-statement here?
        // You probably want to put this line above the previous line instead.
        if (Hunger >= 24)
    }
    // Missing the '{'?
    if (Hunger >= 12)
        changeImage("cry.gif")
// Because here are two '}' while there is only one open
}
}

// Because of these errors, this line will not be reached and thus
// there is no function eat()
function eat() {
    if (Hunger == 6) {
        changeImage("love.gif");
        // Remove 'var' here because otherwise you create a new variable
        // inside this function's closure.
        var Hunger = 0
    } else {
        ...
    }
}

这些很容易修复。如果您需要帮助,请发表评论,我将编辑此答案。

答案 1 :(得分:0)

试试这个:

我已将饥饿变为饥饿

function eat() {
    if (Hunger == 6) {
        changeImage("love.gif");
        Hunger=0;
    }
    else {
        ...
    }
}