问题在于使用时间戳值更新span字段。因此,如果用户A发布了一条消息,它将创建一个插入到dom中的.single-message元素,并具有当前的时间戳。然而,当发生这种情况时,以下代码不会更新:
setInterval(_updateTimestamps, 15000);
function _updateTimestamps()
{
$.each($('[data-timestamp]'), function(index, value) {
var unix = parseInt($(this).attr('data-unix'));
unix = unix * 1000;
var now = new Date().getTime();
var difference = (now - unix) / 1000;
var result = '';
var days = Math.floor(difference / (3600 * 24));
// var weeks = Math.floor(difference / (60 * 60 * 24 * 7));
var weeks = Math.floor(difference / (1000 * 7 * 24 * 60 * 60));
var hours = Math.floor((difference % (60 * 60 * 24)) / (60 * 60));
var minutes = Math.floor(((difference % (60 * 60 * 24)) % (60 * 60)) / 60);
var seconds = Math.floor(((difference % (60 * 60 * 24)) % (60 * 60)) % 60);
if (days > 0) {
result = days + 'd';
$(this).text(result);
return;
}
if (weeks > 0) {
result = weeks + 'w';
$(this).text(result);
return;
}
if (hours > 0) {
result = hours + 'h';
$(this).text(result);
return;
}
if (minutes > 0) {
result = minutes + 'm';
$(this).text(result);
return;
}
if (seconds > 0) {
result = seconds + 's';
$(this).text(result);
return;
}
});
}
为了循环和更新动态创建的DOM元素,我应该怎么做?
发布于 2019-04-08 08:51:50
与使用setInterval方法相比,我建议您使用突变观察者来监视向DOM中动态添加".single-message“元素。下面是伪代码。
var observer = new MutationObserver(function(mutationsList) {
for(var mutation of mutationsList) {
if (mutation.type == 'childList') {
console.log('A child node has been added or removed.');
if(document.querySelectorAll(".single-message").length ! = messageCount){
//update all time stamps here.
}
}
}
});
var messageCount = document.querySelectorAll(".single-message").length;
observer.observe(document.body, {childList: true, subtree: true});
https://stackoverflow.com/questions/55564489
复制相似问题