简体   繁体   English

变异观察者仅获得特定内容

[英]Mutation Observer only get specific content

I have the following structure: 我有以下结构:

<div class="wrapper">
   <div class="col">left</div>
   <div class="col">middle</div>
   <div class="col">right</div>
</div>

Now I want to get the nodes ONLY if INSIDE $('.col') a div of class "block" is included like: 现在,我只想在包含$('。col')类“ block”的div的情况下获取节点,例如:

YES for THIS: 是的:

$('.col')[1].append($('<div class="block">urgent</div>'));

but NO for THIS: 但对此没有:

$('.col')[1].append($('<div class="different">dontcare</div>'));

my Observer looks like this: 我的观察者看起来像这样:

 var observer = new MutationObserver(function (mutations) {
        mutations.forEach(function (mutation) {
            for (var i = 0; i < mutation.addedNodes.length; i++) {
                    console.log(mutation.addedNodes[i]);
                }
            });            
        });

    observer.observe(document, {
        childList: true,
        subtree:true,
        characterData:true,
        attributes:true        
    });

I am inside a chrome extension, but that should not really matter 我在chrome扩展程序内,但这并不重要

Modified your code: 修改您的代码:

  • $('.col')[1].append throw a TypeError, because you use jQuery function on DOM Node, use eq ,ethod $('.col')[1].append引发TypeError,因为您在DOM Node上使用jQuery函数,所以使用eq ,ethod
  • Remove for , add forEach 删除for ,添加forEach

I added the check for .block element in mutation.addedNodes NodeList via addedNode.classList.contains('block') 我通过addedNode.classList.contains('block')mutation.addedNodes NodeList中添加了对.block元素的检查

My code : 我的代码

$(function () {
​
  'use strict';

  var observer = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
      [].slice.call(mutation.addedNodes).forEach(function (addedNode) {
        if (addedNode.classList.contains('block')) {
          console.log("I'm has a class block, whats next?");
        }
      });
    });            
  });
​
  observer.observe(document, {
    childList: true,
    subtree:true,
    characterData:true,
    attributes:true        
  });
​
​
  //Yes
  $('.col').eq(1).append($('<div class="block">urgent</div>'));
​
  //No
  $('.col').eq(1).append($('<div class="different">dontcare</div>'));
​
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM