我需要一些使用 jquery 倒计时的帮助 keith wood - jquery countdown plugin
我通过从 mysql 数据库检索数据(php ajax 调用)并将其放入 div 中来创建几个倒计时:
在 php 中(getdetails.php -> 从 mysql 数据库获取 $mid 和 $time):
$mrow="TimeCounter inserted here:"
$mrow.="<div id=\"RowDiv\"><div id=\"timecount".$mid."\"><script> $('#timecount".$mid."').countdown({until: ".$time."}); </script></div></div>";
$mrow.="TimeCounter ends here";
在JS中我用我得到的数据设置innerHTML:
var url="getDetails.php";
var what="getTimeData";
console.log("call getTimeData");
var p1 = $.post(url,{what:what,selId:selValue,conName:"GId"});
p1.done(function(data){
console.log("Data -> : "+ data);
document.getElementById("CounterDiv").innerHTML=data
});
console.log(data) 显示设置的 html:
<div id="RowDiv" ><div id="timecount2"><script> $('#timecount2').countdown({until: 1454713200}); </script></div></div>
我没有收到任何错误,但我没有看到计数器...我确实看到此处插入了周围的 TimeCounter:TimeCounter 在页面上的此处结束。我认为这是客户端/服务器端问题。也许我需要在使用数据设置innerHTML后再次调用该函数。但我不知道怎么办。
我该如何解决这个问题?有什么想法吗?
最佳答案
您可以在 jQuery.post()
的回调/成功函数中启动计数器,而不是在 HTML 元素中添加内联脚本。为此,您必须更改 PHP 和 JS,如下所示:
PHP
$mrow="TimeCounter inserted here:"
$mrow.="<div id=\"RowDiv\"><div id=\"timecount" . $mid . "\" data-time=\"" . $time . "\"></div></div>";
$mrow.="TimeCounter ends here";
JS
var url = "getDetails.php",
what = "getTimeData";
$.post(url, {what:what,selId:selValue,conName:"GId"}, function(data){
$('#CounterDiv').html(data).find('[id^="timecount"]').countdown({until: $(this).data('time')*1});
});
<小时/>
更新:
我不知道该插件,但调用 .countdown()
时 this
的范围可能会发生变化。在这种情况下,您可以使用 jQuery 的 .each()
函数来传递元素。这样做的方法如下:
$.post(url, {what:what,selId:selValue,conName:"GId"}, function(data){
var $counters = $('#CounterDiv').html(data).find('[id^="timecount"]'),
$el,t;
$counters.each(function(index,element){
$el = $(element);
t = $el.data('time')*1;
$el.countdown({until: t});
});
});
关于javascript - 动态创建的html中的jquery倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35218701/