关于在jQuery的$(document).ready(function(){})里面建立一个时钟的问题

2012-07-24 18:42:29 +08:00
 shuizhongyue
想实现一个动态显示倒计时的效果
$(document).ready(function(){
var count = 120,timerCount;

function timeCount(){
$("#time-count").text(count);
timerCount = setTimeout('timeCount()',1000);
}

timeCount();
});
可是这个效果总是没法实现,在显示120的一秒后控制台提示:timeCount() is not define
表示不理解,这timeCount()函数怎么会找不到
4114 次点击
所在节点    问与答
9 条回复
shuizhongyue
2012-07-24 18:49:17 +08:00
没人对这个问题有兴趣?是这个是很低级的问题还是怎么的
whtsky
2012-07-24 18:53:20 +08:00
function timeCount(){
$("#time-count").text(count);
timerCount = setTimeout('timeCount()',1000);
}

$(document).ready(function(){
var count = 120;

timeCount();
});
shuizhongyue
2012-07-24 18:56:10 +08:00
@whtsky 恩,我知道这样有用,可是我不明白为什么会因为把timeCount()函数的定义放在$(document).ready(function(){})里面之后,就找不到了
endintro
2012-07-24 19:02:57 +08:00
$(document).ready(function(){
var count = 120,timerCount;

function timeCount(){
$("#time-count").text(count);
timerCount = setTimeout(timeCount,1000);
console.log('a');
}

timeCount();
sd4399340
2012-07-24 19:07:54 +08:00
@endintro 为什么用‘timeCount()’不行啊,必须用函数名当参数?
wong2
2012-07-24 19:15:09 +08:00
setTimeout第一个参数填字符串的话,会在全局作用域被执行,而你的timeCount定义在那个匿名函数里,全局下是得不到的
shuizhongyue
2012-07-24 19:18:10 +08:00
@endintro 刚刚试了,这样可以,只是为什么setTimeout('timeCount()',1000)不行呢,我看网上的代码大多是这样写的啊
wong2
2012-07-24 19:23:38 +08:00
@shuizhongyue

String literals are evaluated in the global context, so local symbols in the context where setTimeout() was called will not be available when the string is evaluated as code.

摘自 https://developer.mozilla.org/en/DOM/window.setTimeout

另外还会有和eval一样的安全隐患,最好不要用。。”网上的代码大多是这样写的“。。。= =
benzhe
2012-07-24 19:25:35 +08:00
建议 LZ 了解一下 Javascript 强制类型转换、闭包或作用域链。
setTimeout('timeCount()',1000); 里的 'timeCount()' 被强制转换为 function,并在全局 window 中寻找这个 timeCount ,而 timeCount 只被定义在包内,当然会出错。
@endintro 的方法则是引用包内的 timeCount,也没有转换类型,所以是正常的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/43307

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX