代码之家  ›  专栏  ›  技术社区  ›  Brandon

变异观测器产生无穷环

  •  0
  • Brandon  · 技术社区  · 6 年前

    我正在编写一个函数,使用带有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.');
              }
          }
      };
    

    我也尝试过append/prepend,但是所有的东西都创建了相同的无限循环。像往常一样,我们非常感谢您的帮助。

    当做

    1 回复  |  直到 6 年前
        1
  •  1
  •   juvian    6 年前

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