简体   繁体   English

Javascript读取和更改变量

[英]Javascript reading and changing variables

Ok, I've been up all night try to get this working and i'm a complete javascript newbie 好吧,我已经整晚都试着让这个工作,我是一个完整的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 {
        ...
    }
}

What happens is that when I press the button to trigger it, 当我按下按钮触发它时,会发生什么

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

It changes the image but the hunger doesn't go down 它会改变图像,但饥饿感不会下降

Your JavaScript probably stops working because there are a few syntax errors. 您的JavaScript可能会停止工作,因为存在一些语法错误。 I've added tabs to make it better readable and have added comments to the code to point these errors out: 我添加了标签以使其更易读,并在代码中添加了注释以指出这些错误:

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 {
        ...
    }
}

These are easy to fix. 这些很容易修复。 If you want help with this, just leave a comment and I'll edit this answer. 如果您需要帮助,请发表评论,我将编辑此答案。

Try with this: 试试这个:

I have changed the var Hunger to Hunger 我已将饥饿变为饥饿

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM