簡體   English   中英

在多個新創建的div上使用setInterval

[英]setInterval on multiple new created divs

我想建立一個小型站點,在其中可以顯示不同時區的多重時鍾。 但是我遇到了setInterval函數的問題。

這是我的代碼:

function addClock () {
  $("#container").append('<div class="dclock"></div>');
  setInterval(function () {
    var now = new Date();
    var h = now.getHours();
    var min = now.getMinutes();
    var s = now.getSeconds();

    $(".dclock:last").html(h + ":" + ( min < 10 ? "0" : "" ) + min + ":" + ( s < 10 ? "0" : "" ) + s);
  }, 1000);
}

我有一個按鈕,每次單擊它都會調用addClock函數。 添加一個新時鍾可以正常工作,但是如果我添加第二個時鍾,第一個時鍾可以正常工作。

因為使用最后一個選擇器,所以它們選擇相同的元素。 引用您創建的元素,而不是使用選擇器來選擇它。

function addClock () {
  var div = $("<div class="dclock"></div>"); //new div
  $("#container").append(div);  //add the new div
  setInterval(function () {
    var now = new Date();
    var h = now.getHours();
    var min = now.getMinutes();
    var s = now.getSeconds();

    div.html(h + ":" + ( min < 10 ? "0" : "" ) + min + ":" + ( s < 10 ? "0" : "" ) + s);  //update the html of the div
  }, 1000);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM