mutation observer production infinite loop

99封情书 提交于 2019-12-24 17:06:20

问题


I'm writing a function using the mutation observer with jQuery to register changes to the DOM, specifically when a new node is added so i can change its content:

$("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.');
          }
      }
  };

I've tried append/prepend as well, but everything creates the same infinite loop. As usual, any help is greatly appreciated.

Regards


回答1:


Well, your modification causes another mutation, which results in you modifying it again, causing an infinite loop. A simple solution is to add a class to your element to mark it as already processed, and ignore already processed nodes (nodes that have that class). Another is just check if the dev.morinfo alreade has moreInfoURL inside it, and ignore if it already does



来源:https://stackoverflow.com/questions/50916642/mutation-observer-production-infinite-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!