在以下代码中使用document.getElementById(id).appendChild(img)
会导致浏览器出现问题吗?我想知道如果我在文档的生命周期中多次使用appendChild()更新图像可能会产生内存问题,或者只会创建一个节点? 我知道下面的代码只加载一次图像,但我打算扩展代码以随机更改图像作为动画。该文件将在文件的整个生命周期中多次看到 document.getElementById(id).appendChild(img)
的呼叫。Javascript:多次使用document.getElementById(id).appendChild()?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var img = document.createElement("IMG");
images = new Array();
function random_image(id)
{
var i = 0;
for(i = 0; i < 7; i++)
{
images[i] = "image" + i + ".jpg"
}
var random = (Math.floor(Math.random()*7));
img.src = images[random];
document.getElementById(id).appendChild(img);
}
</script>
</head>
<body onload = "random_image('image')">
<div id="image"></div>
</body>
</html>
你知道,每次追加的东西时会添加其他元素,而不是取代现有的? – kinakuta 2013-02-27 03:42:01
是的,这就是我问这个问题的原因,因为我不太确定如果我在同一个文档中多次使用appendchild()会发生什么。 – pandoragami 2013-02-27 04:03:29