timer_gear只有在我按某个按钮(直到5秒)的情况下才会存在.但是还有另外一个功能,可以随时调用.在此功能中,我清除定时器并重新启动.但首先我必须检查对象是否存在,否则我得到这个错误:
未捕获ReferenceError:未定义timer_gear
未捕获ReferenceError:未定义timer_gear
你能帮我解决吗?这些都不行.
if(timer_gear!="undefined")clearTimeout(timer_gear); if(timer_gear)clearTimeout(timer_gear);
EDIT1:
首先我拼错了我的问题:if(!timer => if(timer
EDIT2:
完整的代码是:
function hide_gear(){ $('#gear_div').animate({opacity: 0},1000); delete timer_gear; //EDIT3: destroy object }
…
/*gear*/ $('#gear').click(function(){ $('#gear_div').animate({ opacity: 1,},1000,function() { timer_gear = setTimeout("hide_gear();",5000); }); }); $('#gear').mousemove(function(){ if( ? ? ? ) { clearTimeout(timer_gear); timer_gear = setTimeout("hide_gear();",5000); } });
结果:
timer_gear// Uncaught ReferenceError timer_gear is not defined timer_gear != undefined // Uncaught ReferenceError: timer_gear is not defined typeof timer_gear !== "undefined" // WORKS typeof timer_gear != "undefined" // WORKS,just tired it var timer_gear; //at the begining - WORKS,but I did not wanted a new variable if its not necessary
谢谢你的答案!
解决方法
第一个应该是:
if(typeof timer_gear !== "undefined"){ clearTimeout(timer_gear); }
而第二,但是这样不行就是timer_gear没有定义,所以你应该使用上面的typeof:
if(timer_gear){ clearTimeout(timer_gear); }