【问题标题】:JQuery: Reload page when Countdown reaches ZeroJQuery:倒计时达到零时重新加载页面
【发布时间】:2017-04-15 10:01:52
【问题描述】:

我正在尝试使用 JQuery 完成倒计时时钟。除了最后一部分,我假装让页面在倒计时达到 0 时重新加载。这就是我所得到的:

1- 首先我创建容器:

var iDiv = document.createElement('div'); 
iDiv.id = 'countdown'; 
iDiv.className = 'countdown';

2- 现在是时钟

// Countdown Clock JQuery
function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        display.text(minutes + ":" + seconds);
        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}
// JQuery function
jQuery(function ($) {
    var fiveMinutes = 60 * 5, 
        display = $('#countdown');
    startTimer(fiveMinutes, display);
    if (fiveMinutes === 0) {
          location.reload();
        }
});

好吧,一切正常,但最后一点:

if (fiveMinutes === 0) {
    location.reload();
    }

页面不会在倒计时达到零时重新加载。有什么想法吗?

【问题讨论】:

    标签: jquery refresh countdown countdowntimer page-refresh


    【解决方案1】:

    你可以通过 setTimeout 重新加载它:

    // JQuery function
    jQuery(function ($) {
        var fiveMinutes = 60 * 5, 
            display = $('#countdown');
        startTimer(fiveMinutes, display);
        setTimeout(function(){ location.reload() }, fiveMinutes*1000);
    });
    

    【讨论】:

    • 非常感谢,这是一种比我达到的解决方案更优雅的方法。我添加了另一个 var 监听计数器达到 0 (00:00),尽管它有效,但它只是一个丑陋的补丁。 var expired = window.setInterval(function(){ if($("*:contains('00:00')").length > 0){ document.location.reload(true); } }, 1000);
    【解决方案2】:

    If 条件仅在第一次执行脚本期间执行一次。此时,fiveMinutes 变量为 60*5 (300) 并且不匹配 === 0 条件。

    // JQuery function
    jQuery(function ($) {
        var fiveMinutes = 60 * 5, 
            display = $('#countdown');
        startTimer(fiveMinutes, display);
        if (fiveMinutes === 0) {
            location.reload();
        }
    });
    

    您需要检查计时器是否运行到0;

    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        display.text(minutes + ":" + seconds);
        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
    

    在定时器值更新内执行条件检查的功能。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多