用于addedNodes的Loop MutationObserver将无法正常运行+ JSFiddle

时间:2017-10-22 06:45:05

标签: javascript jquery

HTML

<body>
    <section class="main-content">
    </section>
</body>

JS

$(document).ready(function() {
    var observer = new MutationObserver(function(mutations) {
        console.log(mutations);
        $.each(mutations, function(k, v) {
            $.each(v.addedNodes, function(k2, v2) {
                $('div.alert', v2[0]).each(function() {
                    $alert = $(this);
                    setTimeout(function() {
                        $alert.fadeOut(1000);
                    }, 2000);
                });
            });
        })
    });
    observer.observe(document, {attributes: false, childList: true, characterData: false, subtree:true});
    $('section.main-content').prepend(
      createAlert({
        type: 'success',
        content: 'success'
      })
    ).prepend(
      createAlert({
        type: 'warning',
        content: 'warning'
      })
    );
});

function createAlert(alert) {
    var alert_default = {
        type: 'primary',
        content: 'Content'
    }
    var alert = $.extend(alert_default, alert);
    return (
        '<div class="alert alert-' + alert.type + ' alert-dismissible fade show" role="alert">' +
            '<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
                '<span aria-hidden="true">&times;</span>' +
            '</button>' +
            alert.content +
        '</div>'
    );
}

代码shoudld fadeOut全部插入<div class"alert">即使它们同时被插入。但它只是不能正常工作,只有fadeOut的最后一个div.alert。

以下是https://jsfiddle.net/u58xezqv/

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

将jQuery对象传递给setTimeout() $alert以引用相同的元素,内嵌式$.each()也不是必需的

  var observer = new MutationObserver(function(mutations) {
    console.log(mutations);
    $.each(mutations, function(k, v) {
      console.log(v);
      $.each(v.addedNodes, function(k2, v2) {
        var $alert = $(v2);
        setTimeout(function(el) {
          el.fadeOut(1000);
        }, 2000, $alert);
      });
    })
  });

jsfiddle https://jsfiddle.net/u58xezqv/3/