2013-11-02 2 views
0

변수가 다른 값보다 크거나 같지 않으면 버튼을 비활성화해야하는 함수를 만들었습니다. 이 함수는 setInterval()에서 매초마다 실행되며 비교할 첫 번째 변수도 setInterval()에서 1 씩 증가합니다. 그러나 함수 (evitarNegs())가 제대로 작동하지 않으며 버튼이 항상 비활성화됩니다. 죄송합니다 코드의 일부가 스페인어로되어 있습니다.if-else 함수가 제대로 작동하지 않습니다.

자바 스크립트 :

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은 개체입니다. http://jsfiddle.net/4rRmp/

: 그래서 당신은

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

그러나,이

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

바이올린만큼 쉽게 쓸 수 있습니다 원하는

1

당신이 GmB >= upg.precio의 정수로 객체를 비교하는 것으로 보인다. 아마도 GmB.cantidad >= upg.precio으로 교체해야 할 것입니다.

관련 문제