【问题标题】:Interval doesn't update text jQuery间隔不更新文本jQuery
【发布时间】:2015-07-13 08:47:32
【问题描述】:

我正在使用 jQuery 和 setInterval 在我的元素中显示倒计时,但它不会更新文本,但是使用 console.log 我可以看到间隔运行正常。这是代码: 我在我的 jQuery 中调用了这个函数:

function startTimer(duration, display) {
  var timer = duration, minutes, seconds,days,hours;
  setInterval(function () {
  days = Math.floor(duration / (60*60*24));
  days_raw = days * (60*60*24);
  hours = Math.floor((duration-days_raw) / (60*60));
  hours_raw = hours * (60*60);
  minutes = Math.floor((duration-(hours_raw + days_raw)) / (60));
  minutes_raw = minutes * (60);
  seconds = Math.floor(duration-(hours_raw + days_raw + minutes_raw));
  seconds_raw = seconds;
  if(days>0)
 {
    if(days===1){
    display.text(days+" Day");
 }
 else
 {
    display.text(days+" Days");}
 }
else if(days<=0)
{   console.log(display);
    display.text(hours+":"+minutes + ":" + seconds);
}

if (--timer < 0) {
  timer = duration;
}
}, 1000);
}

这是我的 jQuery 代码:

jQuery(document).ready(function() {
$('[data-countdown]').each(function() {
 var $this = $(this), finalDate = $(this).data('countdown');
 startTimer(finalDate,$this);
 });
});

.data("countdown") 的值来自一个 php 文件

【问题讨论】:

  • 我删除了 php 标签,因为这与 php 完全无关。
  • @Okonomiyaki3000 我从我的 php 文件中调用这些
  • 那又怎样?这完全无关紧要。
  • 这里有许多泄漏变量进入全局范围。您应该将"use strict"; 放在函数的顶部。
  • 没有正确缩进就无法读取代码。

标签: javascript jquery setinterval


【解决方案1】:

问题是 Duration 的值没有改变,所以我添加了 duration--; if(duration&lt;0) return; 并解决了问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    • 2018-03-30
    • 2018-04-03
    相关资源
    最近更新 更多