javascript - 动态创建的html中的jquery倒计时

标签 javascript php jquery html

我需要一些使用 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/

相关文章:

javascript - 如何从表单的多个字段复制到剪贴板

javascript - 如何重定向到另一个页面并从表中传递 url 中的参数?

javascript - 如何使用 ReactJS 从单选按钮和输入框获取值?

javascript - 获取对象内所有数组的二维数组

php - 如何加载带有 php gd 库的动态图像,不将其保存在服务器上或具有 src ="script.php"?

php - 具有不同用户名的两台服务器之间的故障转移 MYSQL 同步

php - 在 where 子句中使用日期时,Laravel Eloquent 返回空

javascript - 无法专注于 Bootstrap Carousel 中的输入字段

javascript - 如何获取表格中选中的复选框的总数

jquery - 根据设备在 'collapse' 和 'collapse in' 之间进行 Bootstrap 切换