function checkPrice(afford){
var z = document.getElementById('man_cost').innerHTML;
var a = document.getElementById('mouse_cost').innerHTML;
var b = document.getElementById('farm_cost').innerHTML;
var c = document.getElementById('factory_cost').innerHTML;
a = parseInt(a);
b = parseInt(b);
c = parseInt(c);
z = parseInt(z);
if(afford == 'cannot'){
if(amount < z){
document.getElementById('upClick').style.opacity = '.5';
};
if(amount < a){
document.getElementById('upMouse').style.opacity = '.5';
};
if(amount < b){
document.getElementById('upFarm').style.opacity = '.5';
};
if(amount < c){
document.getElementById('upFactory').style.opacity = '.5';
};
}else if(afford == 'can'){
if(amount >= z){
document.getElementById('upClick').style.opacity = '1';
};
if(amount >= a){
document.getElementById('upMouse').style.opacity = '1';
};
if(amount >= b){
document.getElementById('upFarm').style.opacity = '1';
};
if(amount >= c){
document.getElementById('upFactory').style.opacity = '1';
};
};
return;
};
setInterval(checkPrice('can'),1000);
&#13;
setInterval
似乎无法运作。价格每秒更新一次,但如果价格达到可承受的金额,checkPrice
函数不会执行该函数,并且效果不会发生。但是,当我在用户交互后调用setPrice
时,它可以正常工作。
答案 0 :(得分:1)
您需要将其写为:
setInterval(function(){checkPrice('can')},1000);
这是因为第一个参数需要function
,functionName(..)
将给出返回值而不是函数本身。 注意如果函数没有参数,则可以写成:setInterval(checkPrice,1000);
。
答案 1 :(得分:0)
您的var 金额在所有if()
尚未定义,这可能是它无效的原因。
答案 2 :(得分:0)
如果您想在执行中“动态”传递值,请尝试使用bind()
方法。
function checkPrice(){
var afford = this.option;
var z = document.getElementById('man_cost').innerHTML;
var a = document.getElementById('mouse_cost').innerHTML;
var b = document.getElementById('farm_cost').innerHTML;
var c = document.getElementById('factory_cost').innerHTML;
a = parseInt(a);
b = parseInt(b);
c = parseInt(c);
z = parseInt(z);
if(afford == 'cannot'){
if(amount < z){
document.getElementById('upClick').style.opacity = '.5';
};
if(amount < a){
document.getElementById('upMouse').style.opacity = '.5';
};
if(amount < b){
document.getElementById('upFarm').style.opacity = '.5';
};
if(amount < c){
document.getElementById('upFactory').style.opacity = '.5';
};
}else if(afford == 'can'){
if(amount >= z){
document.getElementById('upClick').style.opacity = '1';
};
if(amount >= a){
document.getElementById('upMouse').style.opacity = '1';
};
if(amount >= b){
document.getElementById('upFarm').style.opacity = '1';
};
if(amount >= c){
document.getElementById('upFactory').style.opacity = '1';
};
};
return;
};
setInterval(checkPrice.bind({option: 'afford'}),1000);