倒数计时器未在动态创建的元素内更新

时间:2018-10-08 12:07:12

标签: javascript jquery

CountDown计时器未在动态创建的元素内更新。 我正在尝试在ajax成功之后创建的td内倒数计时器。我将当前服务器时间存储在变量中。 1000ms之后不会更新。

代码如下:

var server_time=`<?php 
                    date_default_timezone_set('Asia/Kolkata');
                    echo date("Y-m-d h:i:s"); 
                    ?>`;
            $.ajax({
                url:'/getCampaigns',
                type:'post',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success:function(response){

                    $.each(response,function(index,element){
                        $('.append_data').append(`<tr><td>${element.id}</td>
                        <td><a href='/campaign-report?campaign_id=${element.id}'>${element.campaign_name}</a></td>
                        <td>${element.total_numbers}</td>
                        <td id="countdown_${element.id}"></td>
                        <td>${element.start_time}</td>
                        </tr>`);

                        /** Countdown Start *****/
                        if(element.status=="Scheduled")
                        {
                            var countDownDate = new Date(`${element.start_time}`).getTime();


                            var x = setInterval(function() {

                            // Get todays date and time
                            var now = new Date(`${server_time}`).getTime();


                            // Find the distance between now and the count down date
                            var distance = countDownDate - now;

                            // Time calculations for days, hours, minutes and seconds
                            var days = Math.floor(distance / (1000 * 60 * 60 * 24));
                            var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                            var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                            var seconds = Math.floor((distance % (1000 * 60)) / 1000);

                            // Display the result in the element with id="demo"
                            $("#countdown_"+element.id).html(days + "d " + hours + "h "
                            + minutes + "m " + seconds + "s ");

                            // If the count down is finished, write some text
                            if (distance < 0) {
                            clearInterval(x);
                            document.getElementById("countdown_"+element.id).innerHTML="Started";
                            }
                            }, 1000);
                            }

1 个答案:

答案 0 :(得分:0)

现在它正在工作。 我删除了php代码,并使用了js new Date();