带有PHP的Jquery倒数计时器未按预期执行

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了带有PHP的Jquery倒数计时器未按预期执行相关的知识,希望对你有一定的参考价值。

我正在使用jquery / php倒数计时器,并且输出与预期不符

下面是下面的代码

<p id='FeedExpire-".$id."' class='FeedExpire' style='display:inline-block;'>".$expires_by_cleaned_new."</p>

拾取p标签的innerhtml内容并循环运行以显示jquery中每个元素的递减计时器

var x = setInterval(function() { 
$('.FeedExpire').each(function () { 
   alert(document.querySelector('#'+this.id).innerHTML);    
   var deadline = new Date(document.querySelector('#'+this.id).innerHTML).getTime();
});

但是没有得到预期的结果。我得到了预期的结果,并且它在瞬间发生了变化(下面的屏幕快照)

下面的完整代码

预期结果

“”

错误

“”

$( document ).ready(function() {            
   $.ajax({
       type: "POST",
       url: "http://192.168.1.11/Retrivedataforhomefeed.php",
       //data: {email:email,userId:userId,displayName:displayName,givenName:givenName,},
       cache: false,
       success: function(data) {
           var results=data;
           document.querySelector('.Homefeedstart').innerHTML = results;
           //alert(document.getElementsById('DBPostExpireBy-1').innerHTML);

           var x = setInterval(function() { 
               $('.FeedExpire').each(function () { 
                   alert(document.querySelector('#'+this.id).innerHTML);   
                   var deadline = new Date(document.querySelector('#'+this.id).innerHTML).getTime();
                   var now = new Date().getTime(); 
                   var t = deadline - now; 
                   var days = Math.floor(t / (1000 * 60 * 60 * 24)); 
                   var hours = Math.floor((t%(1000 * 60 * 60 * 24))/(1000 * 60 * 60)); 
                   var minutes = Math.floor((t % (1000 * 60 * 60)) / (1000 * 60)); 
                   var seconds = Math.floor((t % (1000 * 60)) / 1000); 
                   document.getElementById(this.id).innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s "; 
                   if (t < 0) { 
                       clearInterval(x); 
                       document.getElementById(this.id).innerHTML = "EXPIRED"; 
                   } 
               });
           }, 1000); 
           //});
           //var FeedDatareturned=$(".FeedExpire").attr('id');
           //alert(FeedDatareturned); 
       }
   });
});
<?php
    header('Access-Control-Allow-Headers: X-Requested-With, origin, content-type,');
    header("Access-Control-Allow-Origin: *");
    include("DatabaseConnection.php");
    $sql = $dbh->prepare("SELECT * FROM user_posted_data");
    $sql->execute();
    $row = $sql->fetchAll(PDO::FETCH_ASSOC);
    $terms = array();
    foreach($row as $output) {
        $id=$output['Id'];
        $user_comment = $output['User_comment'];
        $expires_by =$output['Post_expires_by'];
        $expires_by_cleaned = substr($expires_by, 3);
        $expires_by_cleaned_new= substr($expires_by_cleaned, 0, strpos($expires_by_cleaned, 'GMT'));
        $Posted_by = $output['Posted_by'];
        echo"
            <div class='FeedBox' id='FeedBox-".$id."'>
                <img src='img/report.jpg' id='FeedReport-".$id."' alt='Avatar' width='50px' height='50px' style='float:right;'>  
                <img src='img/img_avatar.png' id='FeedImage-".$id."' alt='Avatar' width='50px' height='50px' style='border-radius: 50%;padding-top:10px;padding-left:5px;'>
                <div id='FeedHeader-".$id."' class='FeedHeader'>".$Posted_by."</div> <div id='FeedRadius-".$id."'>Within:100 meters</div>
            <div class='UserComment' id='Data-".$id."'>".$user_comment."</div>
            <div id='HelpExpireText-".$id."' style='display:inline-block;'>lend a hand by:</div><div class='DBPostExpireBy' id='DBPostExpireBy-".$id."' style='display:none;'>".$expires_by_cleaned_new."</div><p id='FeedExpire-".$id."' class='FeedExpire' style='display:inline-block;'></p><div class='ReadMore' id='ReadMore-".$id."' style='display:inline-block;float:right;padding-top:16px;padding-right:5px;' onclick='Nextpage(this);'>Discuss</div></div>";
    }

?>

不确定我要去哪里,请指教

下面的Console.log(截止日期)屏幕截图

“

答案

看看这个。假设时间戳以毫秒为单位,则无需更改PHP您需要将时间戳转换为INT

您不希望在所有计时器到期之前清除间隔。您可以为每个帖子设置一个计时器,也可以使其保持运行状态

success: function(data) {
       var results=data;
       $('.Homefeedstart').html(results);
       startTimers():

将此内容添加到ajax之外的脚本中的其他位置

const pad = num => ("0" + num).slice(-2)
const aSecond = 1000;
const aMinute = aSecond * 60
const anHour = aMinute * 60;
const aDay = anHour * 24;
let x;

function startTimers() {
  clearInterval(x)
  x = setInterval(function() {
    $('.DBPostExpireBy').each(function() {
      let deadline = new Date(+$.trim($(this).text())).getTime();
      let now = new Date().getTime();
      let t = deadline - now;
      let days = Math.floor(t / aDay);
      let hours = Math.floor((t % (aDay)) / (anHour));
      let minutes = Math.floor((t % (anHour)) / (aMinute));
      let seconds = Math.floor((t % (aMinute)) / aSecond);
      let time = t < 0 ? "Expired" : days + "d " + pad(hours) + "h " + pad(minutes) + "m " + pad(seconds) + "s "
      $(this).next().html(time);
    });
  }, 1000);
}

startTimers(); // MOVE this to inside the success
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='FeedBox' id='FeedBox-1'>
  <img src='img/report.jpg' id='FeedReport-1' alt='Avatar' width='50px' height='50px' style='float:right;'>
  <img src='img/img_avatar.png' id='FeedImage-1' alt='Avatar' width='50px' height='50px' style='border-radius: 50%;padding-top:10px;padding-left:5px;'>
  <div id='FeedHeader1' class='FeedHeader'>Posted_by A</div>
  <div id='FeedRadius-1'>Within:100 meters</div>
  <div class='UserComment' id='Data-1'>User A comment</div>
  <div id='HelpExpireText-1' style='display:inline-block;'>lend a hand by:</div>
  <div class='DBPostExpireBy' id='DBPostExpireBy-1' style='display:none;'>1581501796895</div>
  <p id='FeedExpire-1' class='FeedExpire' style='display:inline-block;'></p>
  <div class='ReadMore' id='ReadMore-1' style='display:inline-block;float:right;padding-top:16px;padding-right:5px;' onclick='Nextpage(this);'>Discuss</div>
</div>
<div class='FeedBox' id='FeedBox-2'>
  <img src='img/report.jpg' id='FeedReport-2' alt='Avatar' width='50px' height='50px' style='float:right;'>
  <img src='img/img_avatar.png' id='FeedImage-2' alt='Avatar' width='50px' height='50px' style='border-radius: 50%;padding-top:10px;padding-left:5px;'>
  <div id='FeedHeader1' class='FeedHeader'>Posted_by A</div>
  <div id='FeedRadius-1'>Within:100 meters</div>
  <div class='UserComment' id='Data-1'>User A comment</div>
  <div id='HelpExpireText-1' style='display:inline-block;'>lend a hand by:</div>
  <div class='DBPostExpireBy' id='DBPostExpireBy-1' style='display:none;'>1581501896895</div>
  <p id='FeedExpire-1' class='FeedExpire' style='display:inline-block;'></p>
  <div class='ReadMore' id='ReadMore-1' style='display:inline-block;float:right;padding-top:16px;padding-right:5px;' onclick='Nextpage(this);'>Discuss</div>
</div>
另一答案

请确保您从服务器正确获取了所有数据因为当手动添加日期时代码可以工作]

// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2021 15:37:25").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

  // Get today's date and time
  var now = new Date().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"
  document.getElementById("demo").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";

  // If the count down is finished, write some text
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);
<p id="demo"></p>

以上是关于带有PHP的Jquery倒数计时器未按预期执行的主要内容,如果未能解决你的问题,请参考以下文章

PowerPoint - 创建倒数计时器 - VBA

Jquery UI Datepicker 日历未按预期工作

使用 GCD 计时器间隔播放声音未按预期运行

带有一个 goto 标签的 C 代码未按预期工作

jquery parseHTML 未按预期工作

Javascript:Jquery 发布请求未按预期工作