[英]Function with if-else doesn't work properly
我做了一个函数,如果一个变量不大于或等于另一个变量,则应该禁用按钮。 此函数每秒在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>
您比较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/
似乎您正在将对象与GmB >= upg.precio
的整数进行比较。 您可能必须用GmB.cantidad >= upg.precio
替换它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.