首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >关于动态添加到DOM的元素的jQuery $.each

关于动态添加到DOM的元素的jQuery $.each
EN

Stack Overflow用户
提问于 2019-04-08 07:13:52
回答 1查看 108关注 0票数 0

问题在于使用时间戳值更新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元素,我应该怎么做?

EN

回答 1

Stack Overflow用户

发布于 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});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55564489

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档