如何更新每个唯一的时间戳

时间:2018-02-06 18:12:06

标签: javascript jquery momentjs

我正在使用Moment JS为twitter Feed克隆更新时间戳。

当我向Feed添加新推文时,旧推文的时间戳也会更新。我检查了开发工具,时间戳属性没有更新,所以我不确定为什么它更新。

  var tweetMaker = function(tweet) {
      var $tweet = $('<div></div>');
      // Create HTML Nodes
      var name = document.createElement('span');
      var nameText = document.createTextNode('@' + tweet.user);
      var timeStamp = document.createElement('time');
      var timeStampText = document.createTextNode(moment(tweet.created_at).fromNow());
      var linebreak = document.createElement('br');
      var messageText = document.createTextNode(tweet.message);

      // Add Classes 
      $tweet.addClass('tweet');
      $(timeStamp).addClass('timeStamp');
      $(timeStamp).attr('data-time', tweet.created_at);
      $(name).addClass('name');
      $(name).attr('tweetName', tweet.user);

      // Build Nodes
      name.appendChild(nameText);
      timeStamp.appendChild(timeStampText);
      $tweet.append(name, timeStamp, linebreak, messageText);
      $('#tweetFeed').prepend($tweet)
  }


 //PROBLEM: All timestamps update with new batch of tweets 
  var timeUpdate = function(time) {
    var timeStamp = $('.timeStamp');
    var originalTime = timeStamp.attr('data-time');
    console.log(originalTime)
    timeStamp.html(moment(originalTime).fromNow());
  }

 $(document).ready(function() {
    initialFeed();
    setInterval(timeUpdate, 2000);

    $('.name').on('click', filterByName);
    $('#originalFeed').on('click', showFeed);
    $('#newTweets').on('click', newTweets);
  });
});

1 个答案:

答案 0 :(得分:1)

var timeStamp = $('.timeStamp');将选择所有 .timeStamp 元素。 你应该做这样的事情

var timeUpdate = function(time) {
  var timeStamps = $('.timeStamp');
  timeStamps.each(function (i) {
    var timeStamp  = $(this);
    var originalTime = timeStamp.attr('data-time');
    console.log(originalTime)
    timeStamp.html(moment(originalTime).fromNow());
  });
}