jQuery 功能无法正常工作

jQuery function not working properly

我有一个从网上复制的函数。它在加载时工作正常,但是当我使用 prepend() 添加元素时 spans 已经在其上运行的功能开始闪烁我已将其添加到 jsfiddle 请看一下任何帮助将不胜感激。

$('.b').click(function(){
     $('.top').prepend('<div class="inner">brown fox jumps <span class="sinc"> 1462883724000 </span> </div>');
     $('.sinc').UpdateSince(1000);

});

工作片段:

$.fn.UpdateSince = function(interval) {

  var times = this.map(function() {
    return {
      e: $(this),
      t: parseInt($(this).html())
    };
  });

  var format = function(t) {
    if (t > 86400) {
      return Math.floor(t / 86400) + ' days ago';
    } else if (t > 3600) {
      return Math.floor(t / 3600) + ' hours ago';
    } else if (t > 60) {
      return Math.floor(t / 60) + ' minutes ago';
    } else {
      return t + ' seconds ago';
    }
  }

  var update = function() {
    var now = new Date().getTime();
    $.each(times, function(i, o) {
      o.e.html(format(Math.round((now - o.t) / 1000)));
    });
  };

  window.setInterval(update, interval);
  update();

  return this;
}
$('.sinc').UpdateSince(1000);

$('.b').click(function() {
  $('.top').prepend('<div class="inner">brown fox jumps <span class="sinc"> 1462883724000 </span> </div>');
  $('.sinc').UpdateSince(1000);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div class="top">
  <div class="inner">
    brown fox jumps
    <span class="sinc">1462883724000</span>
  </div>
</div>

<input type="button" class="b" value="click me">

问题是每次单击按钮时都会开始一个新的间隔。您可以 clear the previous interval 在开始新的之前或开始一次间隔并更新列表。

这里有一个清除间隔的例子:

var updateInterval; // Store the interval ID here

$.fn.UpdateSince = function(interval) {

  ...

  // Clear the previous interval
  clearInterval(updateInterval);
  updateInterval = setInterval(update, interval);
  update();

  return this;
};

闪烁是因为 1000 毫秒(1 毫秒)的时间 interval.TRy 将其更改为 30000 以查看差异。

        $('.sinc').UpdateSince(30000);