我创建了一个函数,如果一个变量不大于或等于另一个变量,它应该禁用一个按钮。这个函数在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>发布于 2013-11-02 21:59:01
您正在将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-02 21:58:55
在GmB >= upg.precio中,您似乎正在将一个对象与一个整数进行比较。您可能必须用GmB.cantidad >= upg.precio替换它。
https://stackoverflow.com/questions/19747297
复制相似问题