我正在尝试使用在W3Schools上找到的javascript代码创建倒数计时器。代码一直对我有用,但现在,我需要在php循环中创建定时器,在页面中显示注释。这意味着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 } ?>
我错过了什么?
注意:我使用Code Igniter
答案 0 :(得分:1)
您定义的javascript变量(所有这些变量,包括x = setInterval()
)都是全局的,这意味着它们只应存在一次。所以只有最后一个才会“有效”。你可以像使用span一样伪造''命名空间':
var ExhaustTime<?php echo $comment->id; ?> = "<?php echo $comment_stop_time; ?>";
// the same for countDownDate and x (the setInterval)
这当然不是一个优雅的解决方案,但我认为它会让它发挥作用。
一个优雅的解决方案将所有这些包装在一个类或一个函数中,你将params传递给每个循环。所以你只有一次这个对象,但是在每个循环中调用它(比如init函数)
这样的原始版本可能是这样的:
(未经测试)
// OUTSIDE php foreach loop, so only once in a <script>
function MyCounter(exhaustTime,elementId) {
// this.ExhaustTime = exhaustTime; // there's no need for that extra var
// you might want to check here if you got a valid exhaustTime (or later countDownDate).
this.countDownDate = new Date(exhaustTime).getTime();
this.init = setInterval(function() {
var now = new Date().getTime();
var distance = this.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);
// better find that element only once and re-use it
var target = document.getElementById(elementId);
target.innerHTML = hours + ": " + minutes + ": " + seconds;
if (distance < 0) {
clearInterval(x);
target.innerHTML = "Exhausted!";
}
}, 1000);
}
// inside your php foreach loop (and in a <script>)
var Counter<?php echo $comment->id; ?> = new MyCounter(<?php echo $comment_stop_time; ?>, "cRemTime<?php echo $comment->id; ?>");
Counter<?php echo $comment->id; ?>.init();
进一步阅读:https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS