【问题标题】:making auto-updating, facebook-style time formatting制作自动更新,facebook风格的时间格式
【发布时间】:2012-05-15 10:09:20
【问题描述】:

有人能帮我弄清楚为什么我的 javascript HTML 模板不会自动更新时间,而普通的 HTML 会自动更新时间吗?这是我正在使用的模板库:https://github.com/blueimp/JavaScript-Templates

这是我的 JS(你可以在这里摆弄它:http://jsfiddle.net/trpeters1/SpYXM/76/):

$(document.body).on('click', 'button', function(){
   var id= $(this).data('id');
   var data={id:id, string: "just now...", fxn: nicetime()};       
   var result = tmpl('<div id="string" data-id="'+id+'">{%=o.string%}</div><div id="function" data-id="'+id+'">{%=o.fxn%}</div>', data);     
   $('div[data-id="'+id+'"]').html(result);   
   nicetime();
});

function nicetime(){
  var time =  new Date(),
  var comment_date = setInterval(function() { 
  var time2 = time_since(time.getTime()/1000);
  $('#time_since').html(time2); 
  return time2; 
    }, 
  1000);
}

HTML:

<button data-id="1">1</button>
<div data-id="1"></div>  //tmpl output
<div id="time_since"></div>  //non-tmpl output

【问题讨论】:

  • jquery data()函数与数据属性无关,使用attr()即可。
  • @Musa 谢谢,你对 setInterval 问题有什么建议吗?

标签: javascript templates jquery-templates mustache


【解决方案1】:

你想要this之类的东西。

使用 JavaScript 模板,您通常希望模板 一次,然后动态更新特定元素的值,而不是每秒重置整个元素的 innerHTML。

这是 JavaScript:

$(document.body).on('click', 'button', function(){
    var id= $(this).val(),
        time = +new Date,
        data = {
            id: id,
            string: "just now..."
        },    
        result = tmpl('<span class="string">{%=o.string%}</span>', data),
        tgt = $('#'+id),
        str;
    tgt.html(result);    
    str = tgt.find('.string');
    window.setInterval(function() {
        str.html(time_since(time/1000));
    }, 1000);
});

【讨论】:

  • 太棒了,让我仔细调查一下,但我认为这会奏效!
  • 好的,现在我明白了。将模板值保留为字符串,然后在放置模板后在这些值上查找并运行 setInterval。谢谢!
猜你喜欢
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-02
  • 2010-11-14
  • 2012-06-08
  • 2013-11-20
  • 1970-01-01
相关资源
最近更新 更多