Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/410.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在不递归的情况下使用mutationObserver更改img src?_Javascript_Jquery_Ajax_Mutation Observers - Fatal编程技术网

Javascript 在不递归的情况下使用mutationObserver更改img src?

Javascript 在不递归的情况下使用mutationObserver更改img src?,javascript,jquery,ajax,mutation-observers,Javascript,Jquery,Ajax,Mutation Observers,我试图使用mutationObserver更改图像源,以检查document.body中动态创建的元素,然后相应地更新它们 我怀疑由于我使用的是{attributes:true,subtree:true},因此每次我尝试更新src,都会触发回调,导致页面无响应 有人知道如何解决这个问题吗?我以为我的forEach是问题所在,但即使没有它,问题依然存在。我甚至尝试从mutationObserver返回值,以便在函数中使用,但它只是返回undefined,除非我选择改为console.log 代码如

我试图使用
mutationObserver
更改图像源,以检查
document.body
中动态创建的元素,然后相应地更新它们

我怀疑由于我使用的是
{attributes:true,subtree:true}
,因此每次我尝试更新
src
,都会触发回调,导致页面无响应

有人知道如何解决这个问题吗?我以为我的
forEach
是问题所在,但即使没有它,问题依然存在。我甚至尝试从
mutationObserver
返回值,以便在函数中使用,但它只是返回
undefined
,除非我选择改为
console.log

代码如下:

var target = document.body;
config = {attributes: true, subtree: true}

var makeObserver = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation){

        if (mutation.target.tagName === 'IMG'){
            mutation.target.src = "http://example.com/some_img.jpg";        
            console.log(mutation.target);
        }
    });
});

(function(){
    makeObserver.observe(target, config);   
})();

谢谢

if(mutation.target.tagName=='IMG'&&mutation.target.src!==newURL){
?但是在这里使用MutationObserver听起来像是XY问题。你为什么需要它?你不能控制修改DOM的代码吗?如果是这样,扔掉你的代码,这是危险的;否则,告诉你的代码在需要时也进行img更新。@kaido成功了,谢谢!我想比较一下
,这很有趣==
在某种程度上,但我并不认为这是问题所在。我正在编写一个扩展,因此我无法控制加载内容的方式/时间,也不希望它在带有无限滚动的页面上中断,或者在
onDOMready
之后加载内容(mutation.target.tagName=='IMG'&&mutation.target.src!==newURL){?但是在这里使用MutationObserver听起来像是XY问题。你为什么需要它?你不能控制修改DOM的代码吗?如果是这样,扔掉你的代码,这是危险的;否则,告诉你的代码在需要时也进行img更新。@kaido成功了,谢谢!我想比较一下
,这很有趣==
在某些时候,但我不认为这是问题所在。我正在编写一个扩展,因此我无法控制加载内容的方式/时间,也不希望它在具有无限滚动的页面上中断,或者在
onDOMready
之后加载内容。