V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
shuizhongyue
V2EX  ›  问与答

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

  •  
  •   shuizhongyue · 2012-07-24 18:42:29 +08:00 · 4107 次点击
    这是一个创建于 4295 天前的主题,其中的信息可能已经有所发展或是发生改变。
    想实现一个动态显示倒计时的效果
    $(document).ready(function(){
    var count = 120,timerCount;

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

    timeCount();
    });
    可是这个效果总是没法实现,在显示120的一秒后控制台提示:timeCount() is not define
    表示不理解,这timeCount()函数怎么会找不到
    9 条回复    1970-01-01 08:00:00 +08:00
    shuizhongyue
        1
    shuizhongyue  
    OP
       2012-07-24 18:49:17 +08:00
    没人对这个问题有兴趣?是这个是很低级的问题还是怎么的
    whtsky
        2
    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
        3
    shuizhongyue  
    OP
       2012-07-24 18:56:10 +08:00
    @whtsky 恩,我知道这样有用,可是我不明白为什么会因为把timeCount()函数的定义放在$(document).ready(function(){})里面之后,就找不到了
    endintro
        4
    endintro  
       2012-07-24 19:02:57 +08:00   ❤️ 1
    $(document).ready(function(){
    var count = 120,timerCount;

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

    timeCount();
    sd4399340
        5
    sd4399340  
       2012-07-24 19:07:54 +08:00
    @endintro 为什么用‘timeCount()’不行啊,必须用函数名当参数?
    wong2
        6
    wong2  
       2012-07-24 19:15:09 +08:00   ❤️ 1
    setTimeout第一个参数填字符串的话,会在全局作用域被执行,而你的timeCount定义在那个匿名函数里,全局下是得不到的
    shuizhongyue
        7
    shuizhongyue  
    OP
       2012-07-24 19:18:10 +08:00
    @endintro 刚刚试了,这样可以,只是为什么setTimeout('timeCount()',1000)不行呢,我看网上的代码大多是这样写的啊
    wong2
        8
    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
        9
    benzhe  
       2012-07-24 19:25:35 +08:00   ❤️ 1
    建议 LZ 了解一下 Javascript 强制类型转换、闭包或作用域链。
    setTimeout('timeCount()',1000); 里的 'timeCount()' 被强制转换为 function,并在全局 window 中寻找这个 timeCount ,而 timeCount 只被定义在包内,当然会出错。
    @endintro 的方法则是引用包内的 timeCount,也没有转换类型,所以是正常的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1889 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 16:16 · PVG 00:16 · LAX 09:16 · JFK 12:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.