我正在尝试使用我在 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
最佳答案
您定义的 javascript 变量(所有变量,包括 x= setInterval()
)是全局变量,这意味着它们应该只存在一次。所以只有最后一个是“有效的”。您可以像处理 span 一样伪造“命名空间”它们:
var ExhaustTime<?php echo $comment->id; ?> = "<?php echo $comment_stop_time; ?>";
// the same for countDownDate and x (the setInterval)
这当然不是一个优雅的解决方案,但我认为它会起作用。
一个优雅的解决方案是将所有这些包装在一个类或一个函数中,您在每个循环中将参数传递给该函数。所以你只会有那个对象一次,但在每个循环中调用它(可能像一个初始化函数)
这样的原始版本可能是这样的:
(未测试)
// 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
关于javascript - 在 php foreach 循环中创建一个 javascript 倒数计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46373680/