我想創建一個使用我在W3Schools上找到的JavaScript代碼的倒計時器。代碼一直爲我工作,但現在,我需要在一個php循環中創建一個定時器,該循環在頁面中顯示註釋。這意味着javascript計時器代碼必須對每個評論都是唯一的,並且我已經完成了我的感覺是正確的,但它不起作用。這是我有:在PHP的foreach循環中創建一個JavaScript倒數計時器
<?php
$post_comments = $this->db->get_where('post_comments', array('display' => 'true'))->result_array();
foreach ($post_comments as $comment) { ?>
Expire time - <span id="cRemTime<?php echo $comment->id; ?>" style="color: red"> </span>
<?php
$comment_stop_time = date("M j, Y H:i:s", strtotime($comment->time. '+1 hours')); //timestamp from table + 1 hour
?>
<script>
var ExhaustTime = "<?php echo $comment_stop_time; ?>";
var countDownDate = new Date(ExhaustTime).getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
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);
document.getElementById("cRemTime<?php echo $comment->id; ?>").innerHTML = hours + ": " + minutes + ": " + seconds;
if (distance < 0) {
clearInterval(x);
document.getElementById("cRemTime<?php echo $comment->id; ?>").innerHTML = "Exhausted!";
}
}, 1000);
</script>
<?php } ?>
我錯過了什麼?
注意:我使用代碼點火器
你看過輸出的JavaScript代碼,通過查看頁面源代碼?你在控制檯中看到任何錯誤嗎? – WizardCoder
您定義的js變量(全部包括setInterval函數)都是全局變量,這意味着它們應該只存在一次。所以只有最後一個纔是'有效的'。你可以像'span'一樣僞造「命名空間」 – Jeff