【问题标题】:how to update time regularly?如何定期更新时间?
【发布时间】:2011-07-02 18:57:17
【问题描述】:
function timeClock()
{
    setTimeout("timeClock()", 1000);        
    now = new Date();
    alert(now);
    f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
    return f_date;
}

<span class="foo"><script type="text/javascript">document.write(timeClock());</script></span>

警报(现在);每秒给我一个值,但它没有在 html 中更新。如何在不刷新页面的情况下更新html上的时间?

【问题讨论】:

    标签: javascript jquery datetime


    【解决方案1】:

    您的代码中有许多错误。如果在变量声明前不使用var,您会将它们泄漏到全局范围内。

    另外,document.write 的用法是discouraged

    我会这样做:

    JavaScript:

    function updateClock() {
        var now = new Date(), // current date
            months = ['January', 'February', '...']; // you get the idea
            time = now.getHours() + ':' + now.getMinutes(), // again, you get the idea
    
            // a cleaner way than string concatenation
            date = [now.getDate(), 
                    months[now.getMonth()],
                    now.getFullYear()].join(' ');
    
        // set the content of the element with the ID time to the formatted string
        document.getElementById('time').innerHTML = [date, time].join(' / ');
    
        // call this function again in 1000ms
        setTimeout(updateClock, 1000);
    }
    updateClock(); // initial call
    

    HTML:

    <div id="time"> </div>
    

    【讨论】:

    • 您可能应该用前导零填充now.getMinutes() 调用。
    • 小改进:now.getMonth()+1 应该足够了,而不是传递月份数组。并获得两位数的分钟、秒等: ("0" + now.getMinutes()).slice(-2)
    • @abhy 谢谢你的建议,对我帮助很大!!
    【解决方案2】:

    setInterval(表达式,超时);

    函数 setTimeout 用于单次超时,因此使用 setInterval 将是更合适的选项。 SetInterval 将定期运行,而无需 Ivo 的答案所具有的额外行。

    我将 Ivo 的答案改写如下:

    JavaScript:

    function updateClock() {
      // Ivo's content to create the date.
      document.getElementById('time').innerHTML = [date, time].join(' / ')
    }
    setInterval(updateClock, 1000);
    

    自己试试吧! https://jsfiddle.net/avotre/rtuna4x7/2/

    【讨论】:

      【解决方案3】:
      x = document.getElementsByTagName('SPAN').item(0);
      x.innerHTML = f_date;
      

      尝试用这个代码块代替return 语句,我还没有测试它,但它可能会工作

      【讨论】:

      • 第一次 documrnt.write 显示未定义的值。[2011 年 2 月 23 日 / ISTundefined 下午 7.47]。一秒钟后,它显示了正确的值。
      【解决方案4】:

      可能有一些你可以挂钩的 jQuery 插件,但我还没有真正尝试过......

      http://timeago.yarp.com/

      【讨论】:

        【解决方案5】:
        $('span.foo').html(f_date);
        

        把它放在你的 timeclock() 函数中

        未经测试

            function timeClock()
            {
                setTimeout("timeClock()", 1000);        
                now = new Date();
                alert(now);
                f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
               $('span.foo').html(f_date);
        
        }
        

        【讨论】:

          【解决方案6】:

          我会使用 setInterval 而不是 setTimeout:

          https://developer.mozilla.org/en/DOM/window.setInterval

          【讨论】:

          【解决方案7】:

          我认为你的 setTmeout 函数有错误的变量,第一个应该是函数而不是字符串,这让我有点困惑。基本上你需要在运行函数时写入 span 标签。

          我在小提琴中创建了一个 jQuery 版本来演示我的意思。没有你的 strMonth 函数,但你明白了。我还将警报更改为 console.log,但您可以删除该行。

          http://jsfiddle.net/5JWEV/

          【讨论】:

            【解决方案8】:

            简单的 Javascript 时间格式/更新

            1:创建月份转换函数 2:创建时间函数 3:创建更新函数 4:创建输出函数

                // month converter from index / 0-11 values
            function covertMonth(num){
              let months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
              // look into index with num 0-11
              let computedRes = months[num];
              return computedRes;
            }
            
            // time func
            function Time(){
               // important to get new instant of the Date referrance
              let date = new Date();
              this.time = date.toLocaleTimeString();
              this.year = date.getUTCFullYear();
              this.day = date.getUTCDate();
              this.month = date.getUTCMonth();
              this.currentTime = date.toLocaleTimeString() + ' ' + covertMonth(this.month) + ' ' + this.day + ' ' + this.year;
              return this.currentTime;
            }
            
            
             function timeOutPut(){
              let where = document.getElementById('some-id');
              where.textContent = Time(); // 1:21:39 AM Dec 17 2017
            }
            
               // run every 5secs
            setInterval(timeOutPut, 5000);
            

            【讨论】:

            • 添加一些描述
            【解决方案9】:

            我使用了@soloproper setInterval 概念@Ivo Wetzel 的整体答案,我的更新都是关于根据需要格式化时间。 减少编程线

            <div id="liveClock"> </div>
            
            $(document).ready(function () {
                    updateClock();
            });
            
            function updateClock() {
               document.getElementById('liveClock').innerHTML = new Date().format("dd/MMMM/yyyy hh:mm:ss tt");
            }
            setInterval(updateClock, 1000);
            

            【讨论】:

              【解决方案10】:
              function timeClock()
              {
                  setTimeout("timeClock()", 1000);        
                  now = new Date();
                  alert(now);
                  f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
              
                  document.getElementById("foo").innerHTML = f_date;
              
              }
              
              <span id="foo"></span>
              

              【讨论】:

                猜你喜欢
                • 2021-03-16
                • 2021-11-27
                • 2021-09-07
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2014-11-22
                • 1970-01-01
                相关资源
                最近更新 更多