0

我做了一个函数,如果一个变量不大于或等于另一个变量,它应该禁用一个按钮。此函数在 setInterval() 上每秒运行一次,并且要比较的第一个变量也在 setInterval() 上加一。但是,函数 (evitarNegs()) 无法正常工作,并且该按钮始终处于禁用状态。抱歉,部分代码是西班牙语。

Javascript:

var GmB = {cantidad: 0, perSec: 1};

function Upgrade (pb, ps) {
    this.precioBase = pb;
    this.perSec = ps;
    this.cantidad = 0;
    this.precio = pb;
}

Upgrade.prototype.comprar = function() {
    GmB.cantidad = GmB.cantidad - this.precio;
    GmB.perSec = GmB.perSec + this.perSec;
    this.cantidad++;
    document.getElementById("gmb").innerHTML = GmB.cantidad;
    this.precio = Math.ceil(this.precioBase*Math.pow(1.15, this.cantidad));
    evitarNegs();
};

function loop() {
    GmB.cantidad = GmB.cantidad + GmB.perSec;
    document.getElementById("gmb").innerHTML = GmB.cantidad;
    evitarNegs();
}

var upg = new Upgrade(10, 1);
var boton1 = document.getElementById("boton1");
boton1.disabled = true;
window.setInterval(loop, 1000);

//Problematic function
function evitarNegs() {
    if (!(GmB >= upg.precio)) {
        boton1.disabled = true;
    }else {
        boton1.disabled = false;
    }
}

boton1.onclick = function() {
    upg.comprar();
};

HTML:

<html>
    <head>
        <title>Gummy Bears</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">

    </head>
    <body>
        <p id="gmb">0</p>
        <button id="boton1" type="button">Upgrade 1</button>
        <script src="main.js"></script>
    </body>
</html>
4

2 回答 2

3

您正在比较GmB,upg.precio但是GmB是一个对象。所以你要

function evitarNegs() {
    if (!(GmB.cantidad >= upg.precio)) {
        boton1.disabled = true;
    } else {
        boton1.disabled = false;
    }
}

但是,这可以更容易地编写为

function evitarNegs() {
    boton1.disabled = GmB.cantidad < upg.precio;
}

小提琴:http: //jsfiddle.net/4rRmp/

于 2013-11-02T21:59:01.657 回答
1

您似乎正在将一个对象与GmB >= upg.precio. 您可能必须将其替换为GmB.cantidad >= upg.precio.

于 2013-11-02T21:58:55.673 回答