Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/406.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 DOM附加子替换_Javascript_Html_Css_Dom_Appendchild - Fatal编程技术网

Javascript DOM附加子替换

Javascript DOM附加子替换,javascript,html,css,dom,appendchild,Javascript,Html,Css,Dom,Appendchild,我正在创建一个DOM元素,如下所示 var imgEle = document.createElement('img');     imgEle.src = imgURL;             x.appendChild(imgEle); 现在,对于最后一行,不是每次调用函数时创建多个img元素的追加,而是希望它被替换,或者始终是x的第一个子元素 对于交叉浏览器兼容性,我应该如何执行相同的操作 var xChildren = x.childNodes; if(xChildren[0])

我正在创建一个DOM元素,如下所示

var imgEle = document.createElement('img');
    imgEle.src = imgURL;         
    x.appendChild(imgEle);
现在,对于最后一行,不是每次调用函数时创建多个img元素的追加,而是希望它被替换,或者始终是x的第一个子元素

对于交叉浏览器兼容性,我应该如何执行相同的操作

var xChildren = x.childNodes;
if(xChildren[0])
   x.replaceChild(myIMG, xChildren[0]);
else
   x.appendChild(myIMG);
这应该能奏效

我们抓取X的所有子元素,然后检查第一个元素是否已定义。(如果有多个,也可以使用x.innerHTML方法一次将它们全部删除)。如果定义了它,我们用新创建的元素替换它,如果没有定义,我们只需附加元素

编辑:通过在循环中创建和附加元素,您的脚本有点沉重——既然您似乎只想更改x中包含的图像,为什么不干脆更改.src属性呢

var xChildren = x.childNodes;
var myIMG;    
if(xChildren[0])
   mIMG = xChildren[0]; //you should be sure that this is an image 
   // perhaps you might want to check its type.
else{
   mIMG = document.createElement("img");
   mIMG.src = "source";
   x.appendChild(mIMG);
}

//now the loop
while( your_condition )
    mIMG.src = "source of the image";
这样,您只需使用和编辑一个元素

这应该能奏效

我们抓取X的所有子元素,然后检查第一个元素是否已定义。(如果有多个,也可以使用x.innerHTML方法一次将它们全部删除)。如果定义了它,我们用新创建的元素替换它,如果没有定义,我们只需附加元素

编辑:通过在循环中创建和附加元素,您的脚本有点沉重——既然您似乎只想更改x中包含的图像,为什么不干脆更改.src属性呢

var xChildren = x.childNodes;
var myIMG;    
if(xChildren[0])
   mIMG = xChildren[0]; //you should be sure that this is an image 
   // perhaps you might want to check its type.
else{
   mIMG = document.createElement("img");
   mIMG.src = "source";
   x.appendChild(mIMG);
}

//now the loop
while( your_condition )
    mIMG.src = "source of the image";

这样,您只能使用和编辑一个元素。

Hey..u似乎已经达到了目标..thx很多..而且我总是更喜欢使用x.innerHTML..但是在这种情况下,因为我面临一些问题..所以我使用createElement的方式,.src..最终是否仍有可能使用x.innerHTML?嘿..你似乎已经达到了目标..thx很多..而且我一直希望使用x.innerHTML..但在这种情况下,因为我面临一些问题..所以我使用createElement的方式,.src..最终是否仍有可能使用x.innerHTML?