繁体   English   中英

动态创建的HTML中的jQuery倒数

[英]jquery countdown in dynamically created html

我需要使用jQuery countdown keith wood的一些帮助-jQuery countdown插件

我正在通过从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});
});

更新:我不知道这个插件,但范围this时候可能会改变.countdown()被调用。 在这种情况下,可以使用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});
    });
});

还没有测试代码,但是我的建议是避免发送HTML作为响应,并使getdetails.php使用$mid$time进行响应,例如:

$data = array(
    'mid' => $mid,
    'time' => $time
);
$response = json_encode($data);

您的JS代码应类似于:

var url = "getDetails.php";
var what = "getTimeData";
console.log("call getTimeData");
$.post(url, {what: what, selId: selValue, conName: "GId"}, function (data) {
    console.log("Data -> : " + data);

    var id = 'timecount' + data.mid;
    var row = '<div id="RowDiv"><div id="' + id + '"></div</div>';
    $("#CounterDiv").html(row);
    $('#' + id).countdown({until: data.time});
}, 'json');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM