[英]setInterval on multiple new created divs
I want to build a small site where I can show multible clocs for different time zones. 我想建立一个小型站点,在其中可以显示不同时区的多重时钟。 But I encounterd a problem with the setInterval function.
但是我遇到了setInterval函数的问题。
Here is my code: 这是我的代码:
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);
}
I have a button that calls the addClock function everytime it is clicked. 我有一个按钮,每次单击它都会调用addClock函数。 Adding a new clock works fine but if I add a second clock the first one stoppes working.
添加一个新时钟可以正常工作,但是如果我添加第二个时钟,第一个时钟可以正常工作。
Because you use a last selector so they select the same element. 因为使用最后一个选择器,所以它们选择相同的元素。 reference the element you created instead of using a selector to select it.
引用您创建的元素,而不是使用选择器来选择它。
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.