jQuery $ .each关于向DOM动态添加元素

时间:2019-04-07 23:13:52

标签: javascript jquery

问题在于使用时间戳值更新跨度字段。因此,如果用户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元素

1 个答案:

答案 0 :(得分:0)

建议您不要使用setInterval方法,而应使用突变观察器来监视“ .single-message”元素向DOM的动态添加。这是伪代码。

 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});