变异观察者产生无限循环

Bra*_*don 3 javascript jquery moodle

我正在使用 jQuery 的突变观察器编写一个函数来注册对 DOM 的更改,特别是在添加新节点时,以便我可以更改其内容:

$("SELeCTOR GOOD" ).click(function(){
  var targetNode = $(this).find('.content').get(0);
  var config = { attributes: true, childList: true, subtree: true, attributeOldValue: true };

  // Callback function to execute when mutations are observed
  var callback = function(mutationsList) {
      for(var mutation of mutationsList) {
          if (mutation.type == 'childList') {
              var courses = $(targetNode).find('.courses').get(0);
              $(courses).find('.coursebox.clearfix').each(function( index,item ) {
                var attacherURL = $(item).find('.coursename a').attr('href');
                var moreInfoURL = '<a class="btn btn-outline-primary pull-right" href="'+attacherURL+'">More info</a>';

                var oldHTML = $(item).find('div.moreinfo').html();
                var newHTML = moreInfoURL + oldHTML;
                //this following line is supposed to replace the html, but it creates an infinite loop
                $(item).find('div.moreinfo').html(newHTML);
                //end
              });
          }
          else if (mutation.type == 'attributes') {
              console.log('The ' + mutation.attributeName + ' attribute was modified.');
          }
      }
  };
Run Code Online (Sandbox Code Playgroud)

我也尝试过追加/前置,但一切都会创建相同的无限循环。与往常一样,我们非常感谢任何帮助。

问候

juv*_*ian 6

好吧,你的修改会导致另一个突变,这会导致你再次修改它,从而导致无限循环。一个简单的解决方案是向元素添加一个类以将其标记为已处理,并忽略已处理的节点(具有该类的节点)。另一个方法是检查 dev.morinfo 中是否已经有 moreInfoURL ,如果已经有,则忽略