2011-06-11 43 views
0

我正在创建DOM元素,如下所示;DOM appendChild备选

var imgEle = document.createElement('img'); 
    imgEle.src = imgURL;         
    x.appendChild(imgEle); 

现在最后一行,而不是追加其创建多个IMG元素每个函数被调用时,我希望它被替换或永远是x的第一个子元素..

应该如何我为crossbrowser兼容性做同样的事情吗?

回答

4
var xChildren = x.childNodes; 
if(xChildren[0]) 
    x.replaceChild(myIMG, xChildren[0]); 
else 
    x.appendChild(myIMG); 

应该做的伎俩

我们抓住X的所有子元素,然后我们检查,看看他们的第一个定义。 (如果有多个,您也可以使用x.innerHTML方法一次全部删除它们)。如果定义了它,我们用新创建的元素替换它,如果它不是 - 我们简单地追加元素。

编辑:通过在一个循环中创建和追加元素,你使你的脚本有点沉重 - 因为它似乎只想改变x中包含的图像,为什么不简单地使用chaning .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"; 

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

+0

Hey..u似乎已经得到了这个目标..很多..此外,我会一直喜欢使用x.innerHTML ..但在这种情况下,因为即时通讯面临一些问题..所以即时通讯做使用createElement,.src ..它仍然有可能在最后使用x.innerHTML? – testndtv 2011-06-11 17:04:44