Jquery Countdowntimer 错误地为多个跨度显示相同的计时器

Jquery Countdowntimer shows same timer for multiple spans in error

本文关键字:显示 计时器 错误 Countdowntimer Jquery      更新时间:2023-09-26

我有一个包含游戏详细信息的表格。 我想为每场比赛添加一个计数停机时间。

我正在使用jquery-countdownTimer plugin

我的网页:

<span class="given_date" data-gamestart="2016/3/11 15:30"></span>
<span class="given_date" data-gamestart="2016/3/13 18:00"></span>
<span class="given_date" data-gamestart="2016/3/15 17:45"></span>
<span class="given_date" data-gamestart="2016/3/22 19:45"></span>

我使用这个插件来倒计时。

我的js:

$('.given_date').countdowntimer({
            dateAndTime : "2016/3/10 17:05"
});

一个jsFiddle示例

我的问题是,即使我为每个跨度提供了不同的时间,所有计时器也会同步显示相同的值和倒计时

为什么每个跨度不根据我提供的值显示自己的计时器?

您的问题是您的元素没有ids.

该插件使用以下代码设置计时器,然后显示其值。请注意window['regexpMatchFormat_' + $this.attr('id')] 。这使用每个元素的 id 创建一个唯一的全局变量来跟踪计时器。如果你的元素没有id,你最终会反复覆盖你的第一个计时器

//Code for starting the timers.
        if (options.regexpMatchFormat != undefined && options.regexpReplaceWith != undefined && options.timeSeparator == undefined) {
            window['regexpMatchFormat_' + $this.attr('id')] = options.regexpMatchFormat;
            window['regexpReplaceWith_' + $this.attr('id')] = options.regexpReplaceWith;
        }

//Function for displaying the timer.
function html($this, content) {
    var processedContent = content;
    if (typeof window['regexpMatchFormat_' + $this.attr('id')] !== 'undefined' &&
            typeof window['regexpReplaceWith_' + $this.attr('id')] !== 'undefined') {
        var regexp = new RegExp(window['regexpMatchFormat_' + $this.attr('id')]);
        processedContent = content.replace(regexp,
                window['regexpReplaceWith_' + $this.attr('id')]);
    }
    $this.html(processedContent);
}

工作 js小提琴

这就是为什么您应该始终链接到您正在使用的插件;)

最好的方法是使用 jQuery 的.each()遍历span,并在该循环中设置 countdowntimer。像这样:

$('.given_date').each(function() {
    $(this).countdowntimer({
        dateAndTime : this.getAttribute("data-gamestart")
    });
});