在花了45分钟寻找解决方案后,我似乎找不到一个简单的解决方案来使用PHP和jQuery创建倒计时计时器。我发现大多数已经构建的脚本都是纯粹基于jQuery的,这需要大量的代码,并且需要更多的参数,而且适应性非常困难。
这是我的情况;
PHP:
$countdown = date("h:i:s"); // This isn't my actual $countdown variable, just a placeholder
jQuery:
$(document).ready(function name() {
$("#this").load( function() {
setTimeout("name()", 1000)
}
}
});HTML:
<div id="this"><?php echo($countdown); ?></div>
我的想法是,每秒都会重新加载#this,为其内容赋予一个新值,而且由于$countdown不是静态变量,所以每次都会加载一个新值。这消除了处理会话的需要(因为基本的javascript倒计时器会在页面加载时重置,等等)。
我本以为这会起作用,直到我意识到事件绑定器.load()不会重新加载#this (我知道我很傻),所以我猜我想知道的是-有没有事件绑定器可以让这件事起作用,或者有没有办法在不使用jQuery插件的情况下获得我想要的功能(它无论如何都不完全符合我想要的)?
发布于 2011-08-19 08:16:36
你应该使用基思·伍德的倒计时器:http://keith-wood.name/countdown.html
它非常容易使用。
你所要做的就是
$('#timer').countdown({
until: '<?php echo date("h:i:s"); ?>' // change this, obviously
});这就是问题所在:http://jsfiddle.net/tqyj4/289/
发布于 2011-08-19 08:14:35
好吧,我知道ID不是一个变量,但是不要使用this作为id,它会让人感到畏缩。
对于其余的,不要重新加载值,在PHP中设置JS中的值,然后倒计时。
// place this in the <head> above the code below
echo "var t = " . time() . ";";
echo "var ft = " . /* your final time here */ . ";";然后:
// this is a helper function.
function lpad( input, len, padstr )
{
if( !padstr ) padstr = " "; // this is the normal default for pad.
var ret = String( input );
var dlen = ret.length - len;
if( dlen > 0 ) return ret;
for( var i = 0; i < dlen; i++ ) ret = padstr + ret;
return ret;
}
$(document).ready(function name() {
$("#timer").load( function() { // I changed the id
$timer = $("timer"); // might as well cache it.
// interval, not timeout. interval repeats
var intval = setInterval(function(){
t += 500; // decrease the difference in time
if( t >= ft )
{
t = ft; // prevent negative time.
clearInterval( intval ) // cleanup when done.
}
var dt = new Date(ft - t);
$timer.innerHTML = dt.getHours() + ":" +
// pad to make sure it is always 2 digits
lpad( dt.getMinutes(), 2, '0' ) + ":" +
lpad( dt.getSeconds(), 2, '0' );
}, 500) // increments of .5 seconds are more accurate
}
}
});发布于 2011-08-19 08:17:05
一旦php为用户加载了特定的时间,你能解释为什么这不足以满足你的需求吗:
$(function(){
$timerdiv = $("#this");
timer();
});
function timer()
{
$timerdiv.html((int)$timerdiv.html() - 1);
setTimeout(timer, 1000);
}https://stackoverflow.com/questions/7115620
复制相似问题