DOM appendChild 替代
我正在创建一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这应该可以解决问题。
我们正在获取 X 的所有子元素,然后检查它们中的第一个是否已定义。 (如果有多个,您也可以使用 x.innerHTML 方法一次性将其全部删除)。如果已定义,我们将其替换为新创建的元素,如果未定义,我们只需附加该元素即可。
编辑:通过在循环中创建和附加元素,您的脚本有点繁重 - 因为您似乎只想更改 x 中包含的图像,为什么不简单地诉诸于更改 .src 属性?
这样,您只需使用和编辑一个元素。
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?
This way, you 're only using and editing one element.