突变观察者产生无限循环
mutation observer production infinite loop
我正在编写一个函数,使用带有 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,但一切都会产生相同的无限循环。像往常一样,非常感谢任何帮助。
此致
嗯,你的修改导致了另一个突变,导致你再次修改它,导致死循环。一个简单的解决方案是向您的元素添加一个 class 以将其标记为已处理,并忽略已处理的节点(具有 class 的节点)。另一个是检查 dev.morinfo 里面是否已经有 moreInfoURL,如果已经有就忽略
我正在编写一个函数,使用带有 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,但一切都会产生相同的无限循环。像往常一样,非常感谢任何帮助。
此致
嗯,你的修改导致了另一个突变,导致你再次修改它,导致死循环。一个简单的解决方案是向您的元素添加一个 class 以将其标记为已处理,并忽略已处理的节点(具有 class 的节点)。另一个是检查 dev.morinfo 里面是否已经有 moreInfoURL,如果已经有就忽略