2013-11-02 43 views
0

我做了一個功能,應該禁用一個按鈕,如果一個變量不大於或等於另一個。該函數在setInterval()中每秒運行一次,並且第一個要比較的變量也在setInterval()上加1。但是,函數(evitarNegs())工作不正常,並且按鈕始終處於禁用狀態。對不起,部分代碼是西班牙文。功能與if-else不能正常工作

的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> 

回答

3

您正在比較GmBupg.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/

1

看來,你是在GmB >= upg.precio對象比較爲整數。您可能必須將其替換爲GmB.cantidad >= upg.precio