shuizhongyue
V2EX  ›  问与答

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

  •  
  •   shuizhongyue · Jul 24, 2012 · 5165 views
    This topic created in 5065 days ago, the information mentioned may be changed or developed.
    想实现一个动态显示倒计时的效果
    $(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 replies    1970-01-01 08:00:00 +08:00
    shuizhongyue
        1
    shuizhongyue  
    OP
       Jul 24, 2012
    没人对这个问题有兴趣?是这个是很低级的问题还是怎么的
    whtsky
        2
    whtsky  
       Jul 24, 2012
    function timeCount(){
    $("#time-count").text(count);
    timerCount = setTimeout('timeCount()',1000);
    }

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

    timeCount();
    });
    shuizhongyue
        3
    shuizhongyue  
    OP
       Jul 24, 2012
    @whtsky 恩,我知道这样有用,可是我不明白为什么会因为把timeCount()函数的定义放在$(document).ready(function(){})里面之后,就找不到了
    endintro
        4
    endintro  
       Jul 24, 2012   ❤️ 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  
       Jul 24, 2012
    @endintro 为什么用‘timeCount()’不行啊,必须用函数名当参数?
    wong2
        6
    wong2  
       Jul 24, 2012   ❤️ 1
    setTimeout第一个参数填字符串的话,会在全局作用域被执行,而你的timeCount定义在那个匿名函数里,全局下是得不到的
    shuizhongyue
        7
    shuizhongyue  
    OP
       Jul 24, 2012
    @endintro 刚刚试了,这样可以,只是为什么setTimeout('timeCount()',1000)不行呢,我看网上的代码大多是这样写的啊
    wong2
        8
    wong2  
       Jul 24, 2012
    @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  
       Jul 24, 2012   ❤️ 1
    建议 LZ 了解一下 Javascript 强制类型转换、闭包或作用域链。
    setTimeout('timeCount()',1000); 里的 'timeCount()' 被强制转换为 function,并在全局 window 中寻找这个 timeCount ,而 timeCount 只被定义在包内,当然会出错。
    @endintro 的方法则是引用包内的 timeCount,也没有转换类型,所以是正常的
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2566 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 01:41 · PVG 09:41 · LAX 18:41 · JFK 21:41
    ♥ Do have faith in what you're doing.