我正在處理將頁面拆分爲兩個div元素然後在左側添加隨機放置圖像的div,然後我使用.cloneNode()
在右側複製,減去最後一個子圖像。lastElementChild返回null
它的那部分工作正常,但我應該添加一個事件處理程序到左div的最後一個元素,但是當我嘗試執行此操作時,lastElementChild()
方法返回null,即使div有預期的子節點節點。代碼如下,我已經評論了問題出在哪裏。任何幫助,將不勝感激!
<!DOCTYPE html>
<html>
<head>
<style>
img {position: absolute}
div {position: absolute; height: 500px; width: 500px}
#right {border-left: solid black; left: 500px}
</style>
<script>
<!-- everything here works fine -->
function generateFaces(){
var theLeftSide = document.getElementById("left");
var numberFaces = 5;
for (i = 0; i < numberFaces; i++){
var random_x = Math.random()*400;
var random_y = Math.random()*400;
var image = document.createElement("img")
image.src = "smile.png";
image.setAttribute("style","top: " + random_y + "px;" + "left: " + random_x + "px;");
theLeftSide.appendChild(image);
}
var theRightSide = document.getElementById("right");
leftSideImages = theLeftSide.cloneNode(true);
theRightSide.appendChild(leftSideImages);
theRightSide.lastChild.removeChild(theRightSide.lastChild.lastChild);
}
</script>
</head>
<body onload = "generateFaces()">
<h1> Game </h1>
<p> Instructions </p>
<div id = "right"></div>
<div id = "left"> </div>
<script>
<!-- problem script here -->
var temp = document.getElementById("left");
console.log(temp); // displays <div> with its children <img>
var temp2 = temp.lastElementChild;
console.log(temp2); // returns null
</script>
</body>
</html>
'generateFaces()'後,你的名字叫做'的console.log (TE MP2)'。當你登錄時,'#left'仍然是一個空的'div' – Thomas