变异观察者产生无限循环 [英] mutation observer production infinite loop

查看:135
本文介绍了变异观察者产生无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

致谢

推荐答案

好,您的修改会导致另一个突变,导致您再次对其进行修改,从而导致无限循环.一个简单的解决方案是在您的元素中添加一个类,以将其标记为已处理,然后忽略已处理的节点(具有该类的节点).另一个只是检查dev.morinfo是否已包含moreInfoURL,并忽略它是否已经存在

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

这篇关于变异观察者产生无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆