shuizhongyue
V2EX  ›  问与答

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

  •  
  •   shuizhongyue · Jul 24, 2012 · 5516 views
    This topic created in 5218 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
    shuizhongyue
    OP
    Jul 24, 2012
    1
    没人对这个问题有兴趣?是这个是很低级的问题还是怎么的
    whtsky
    whtsky
    Jul 24, 2012
    2
    function timeCount(){
    $("#time-count").text(count);
    timerCount = setTimeout('timeCount()',1000);
    }

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

    timeCount();
    });
    shuizhongyue
    shuizhongyue
    OP
    Jul 24, 2012
    3
    @whtsky 恩,我知道这样有用,可是我不明白为什么会因为把timeCount()函数的定义放在$(document).ready(function(){})里面之后,就找不到了
    endintro
    endintro
    Jul 24, 2012❤️1
    4
    $(document).ready(function(){
    var count = 120,timerCount;

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

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