在以下代碼中使用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