DOM appendChild 替代

发布于 2024-11-15 06:12:22 字数 294 浏览 4 评论 0原文

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

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

现在,对于最后一行,而不是每次调用函数时添加创建多个 img 元素,我希望它被替换或始终是 x 的第一个子元素。

我应该如何做同样的事情来实现跨浏览器兼容性?

I am creating a DOM element as follows;

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

Now for the last line instead of appending which creates multiple img elements each time the function is called, I want it to be replaced OR always be the first child element of x..

How should i do the same for crossbrowser compatibility?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忆悲凉 2024-11-22 06:12:22
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";

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

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

that should do the trick

We are grabbing all the child Elements of X, and then we check to see if the first of them is Defined. (If there are more than one you can also use the x.innerHTML method to remove them all at once). If it is defined we replace it with our newly created element, if it is not - we simply append the element.

EDIT: By creating and appending elements in a loop, you 're making your script a bit heavy - since it seems that you want to just change the image contained within x, why don't you simply resort to chaning the .src attribute?

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";

This way, you 're only using and editing one element.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文