请帮助MutationObserver脚本

时间:2016-02-07 11:54:51

标签: javascript jquery html mutation-observers

请帮忙写一下,我对javascript一点也不好。

我有这样的代码:

<ul id="theul">
   <li id="firstli" style="display: something;"></li>
   <li id="secondli" style="display: something;"></li>
   <li id="thirdli" style="display: something;"></li>
</ul>

我想要一个脚本来检测DOM中关于&#34; display: something&#34;的变化。在所有这些<li>标记中。

如果&#34; display: none&#34; =&GT;添加&#34; someattribute="value"&#34;并删除&#34; anotherattrubute="anothervalue"&#34;

如果它&#34; display: block&#34; =&GT;添加&#34; anotherattrubute="anothervalue"&#34;并删除&#34; someattribute="value"&#34;

我很遗憾只知道HTML和CSS而且从未处理过javascripting,请你给我一个如何做到这一点的例子,以便我将它应用到我的网站

我忘了添加我在这里找到的脚本,但无法应用它,因为我不知道javascript。

window.MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
// Find the element that you want to "watch"
var target = document.querySelector("#demo");
// create an observer instance
observer = new MutationObserver(function(mutation) {
     /** this is the callback where you
         do what you need to do.
         The argument is an array of MutationRecords where the affected attribute is
         named "attributeName". There is a few other properties in a record
         but I'll let you work it out yourself.
      **/
mutations.forEach(function(mutation) {
      if (mutation.type === 'childList') {
        var list_values = [].slice.call(list.children)
            .map( function(node) { return node.innerHTML; })
            .filter( function(s) {
              if (s === '<br />') {
                return false;
              }
              else {
                return true;
              }
        });
        console.log(list_values);
      }
    });
});
// configuration of the observer:
config = {
    attributes: true // this is to watch for attribute changes.
};
// pass in the element you wanna watch as well as the options
observer.observe(target, config);
// later, you can stop observing
// observer.disconnect();

1 个答案:

答案 0 :(得分:0)

如果你正在使用jQuery,请考虑这个插件:https://github.com/eclecto/jQuery-onMutate

使用该插件,语法将是这样的,其中 doSomething 是回调函数。

$('#theul > li').onModify('style', doSomething, true);