div的单独倒计时 [英] separate countdown for divs

查看:149
本文介绍了div的单独倒计时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在每个div中显示倒数计时.现在,我从数据库中获取秒数并存储在data-countdown属性中,然后使用以下js代码进行倒计时.仅第一个div每秒钟更改一次该值,而其他div不变. 这是小提琴: http://fiddle.jshell.net/j61qs7oc/

I want to show countdown in each of my divs. Right now I get the seconds from my database and store in in data-countdown attribute and then use the following js code for countdown. Only the first div changes the value every second and the other ones do not change. Here is the fiddle: http://fiddle.jshell.net/j61qs7oc/

//imagine this line of code in every loop of a for loop so $remaining will be different
<div style="font-size: 25px; color:#e3b40b ; font-weight: 600;" data-countdown="'.$remaining.'"><i class="fa fa-spinner fa-pulse"></i></div>

这是js代码

$('[data-countdown]').each(function() {

finalDate = $(this).data('countdown');
var $this = $(this);
timeout = null;
time = null;
startCountdown($this,finalDate, 1000, end);

function startCountdown(display,timen, pause, callback) {
    time = timen;
    display.html(timen);

    if (timen == 0)
        callback();
    else {
        clearTimeout(timeout);
        timeout = setTimeout(function () {
            startCountdown(display,timen - 1, pause, callback)
        }, pause);
    }
}

function end() {
    alert();
}
});

推荐答案

在不使用var关键字声明变量时,将创建一个全局变量.因此,每个倒计时实例都会覆盖finalDatetimeouttime的先前值.尝试在每行之前添加var,它应该可以满足您的需求.即:

When you declare a variable without using the var keyword, you're creating a global. So each instance of your countdown is overwriting the previous value of finalDate, timeout, and time. Try adding var before each of those lines and it should do what you need. i.e.:

var finalDate = $(this).data('countdown');
var $this = $(this);
var timeout = null;
var time = null;
startCountdown($this,finalDate, 1000, end);

这篇关于div的单独倒计时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆