各位!我是 html/css/javascript 的新手。 我正在 Coursera 上学习这类类(class)。 在程序中,我尝试用“theRightSide”复制“theLeftSide”,并删除“theRightSide”中的最后一张图片。 我已经尝试了两天的所有方法。但无法修复它。 Chrome 显示“未捕获的类型错误:无法读取 null 的属性‘parentNode’”。 谁能告诉我错误在哪里?非常感谢!!!
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
<style>
img {position: absolute;}
div {position: absolute;width: 500px;height: 500px;}
#rightside {left: 500px;border-left: 1px solid black;}
</style>
</head>
<body onload="generateFaces()">
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left</p>
<div id="leftside"></div>
<div id="rightside"></div>
<script>
var numberOfFaces=5;
var theLeftSide=document.getElementById("leftside");
var theRightSide=document.getElementById("rightside");
function generateFaces(){
for (var i = 0; i <numberOfFaces; i++) {
var pic=document.createElement("img");
pic.src="smile.png";
pic.style.top=Math.random()*400+"px";
pic.style.left=Math.random()*400+"px";
theLeftSide.appendChild(pic);
};
}
var leftSideImages=theLeftSide.cloneNode(true);
var last_child=leftSideImages.lastChild;
last_child.parentNode.removeChild(last_child);
theRightSide.appendChild(leftSideImages);
</script>
</body>
</html>
最佳答案
将lastchild放在body load函数中:
function generateFaces(){
for (var i = 0; i <numberOfFaces; i++) {
var pic=document.createElement("img");
pic.src="smile.png";
pic.style.top=Math.random()*400+"px";
pic.style.left=Math.random()*400+"px";
theLeftSide.appendChild(pic);
};
var leftSideImages=theLeftSide.cloneNode(true);
var last_child=leftSideImages.lastChild;
last_child.parentNode.removeChild(last_child);
theRightSide.appendChild(leftSideImages);
}
在有图像之前触发。 函数 generateFaces() 在加载正文后开始,但其余代码会尽快运行,因此当它运行时,其中还没有 child 。 希望对您有所帮助。
关于javascript - 使用javascript删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34112196/