Javascript .removeChild & .appendChild 不工作
我正在尝试使用一个非常简单的 Javascript 函数来工作,该函数将使用 .removeChild 和 .appendChild 将一张图像更改为另一张图像。我的代码如下:
<html>
<head>
<script type="text/javascript" language="javascript">
function bannerload(){
var banner = new Image();
banner.src = "IMG/banner.gif";
var loading = new Image();
loading.src = "IMG/loading.gif";
var bannerElement = document.getElementById("BANNER");
bannerElement.removeChild(banner);
bannerElement.appendChild(loading);
}
</script>
</head>
<body onload="bannerload()">
<div id="BANNER">
<img src="IMG/banner.gif" alt="Banner" />
</div>
</body>
</html>
但是,它不起作用。该页面只是加载了banner.gif,并且该图像从未更改为loading.gif。我不明白为什么,请帮忙?!
谢谢!
I'm trying to get a very simple Javascript function to work that will change one image for another using .removeChild and .appendChild. My code is as follows:
<html>
<head>
<script type="text/javascript" language="javascript">
function bannerload(){
var banner = new Image();
banner.src = "IMG/banner.gif";
var loading = new Image();
loading.src = "IMG/loading.gif";
var bannerElement = document.getElementById("BANNER");
bannerElement.removeChild(banner);
bannerElement.appendChild(loading);
}
</script>
</head>
<body onload="bannerload()">
<div id="BANNER">
<img src="IMG/banner.gif" alt="Banner" />
</div>
</body>
</html>
However, it's not working. The page just loads up with banner.gif and this image is never changed to loading.gif. I can't figure out why, some help pls?!
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不起作用的原因是您正在尝试添加一个子项并删除一个不是子项的子项。
您正尝试从名为 BANNER 的元素中删除名为 BANNER 的子元素。
显然,名为 BANNER 的元素没有名为 Banner 的子元素。您有两种选择,要么为子元素提供 id 并调用“banner.parent.removeChild(banner)”,要么执行以下操作:
示例片段
The reason this doesn't work is you are trying to add a child and remove a child that isn't a child.
You are trying to remove the child named BANNER from the element named BANNER.
Obviously the element named BANNER doesn't have a child named banner. You have two choices either give the id to the child element and call `banner.parent.removeChild(banner) or the following:
Example snipet
我认为你的问题是你试图删除bannerElement 中不存在的子元素。
看看如何制作新图像然后将其删除,即使您尚未附加它?我认为你应该尝试这样的事情:
I think your problem is that you're trying to remove a child that doesn't exist in the bannerElement.
See how you're making a new image and then removing it, even though you didn't append it yet? I think you should try something like this: