簡體   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