无法读取属性“的appendChild”空
问题描述:
。这是我的代码,我在Java脚本初学者。无法读取属性“的appendChild”空
<!doctype html>
<html>
<head>
<style>
div {position:absolute; width:500px; height:500px}
img {position:absolute}
#rightSide { left: 500px;
border-left: 1px solid black }
</style>
<script>
function generateFaces() {
var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
var theRightSide = document.getElementById("rightside");
for (var i = 1; i <= numberOfFaces; i++) {
this_img = document.createElement("img");
this_img.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
var topIndex = Math.floor(Math.random() * 401);
var leftIndex = Math.floor(Math.random() * 401);
this_img.style.top = topIndex + "px";
this_img.style.left = leftIndex + "px";
this_img.style.position = "absolute";
theLeftSide.appendChild(this_img);
theLeftimages = document.cloneNode(true);
theLeftimages = theLeftimages.removeChild(theLeftimages.lastChild);
theRightSide.appendChild(theLeftimages);
};
}
</script>
</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>
</body>
</html>
其中发生问题的部分在功能上产生面
function generateFaces() {
var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
var theRightSide = document.getElementById("rightside");
for (var i = 1; i <= numberOfFaces; i++) {
this_img = document.createElement("img");
this_img.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
var topIndex = Math.floor(Math.random() * 401);
var leftIndex = Math.floor(Math.random() * 401);
this_img.style.top = topIndex + "px";
this_img.style.left = leftIndex + "px";
this_img.style.position = "absolute";
theLeftSide.appendChild(this_img);
theLeftimages = document.cloneNode(true);
theLeftimages = theLeftimages.removeChild(theLeftimages.lastChild);
theRightSide.appendChild(theLeftimages);
};
}
; 它显示一个错误
Uncaught TypeError: Cannot read property 'appendChild' of null.
,我不能克隆图像右侧股利。
答
JavaScript是区分大小写的。它应该是rightSide
var theRightSide = document.getElementById("rightSide");
由于没有得到的元素,它返回NULL以theRightSide,这显然不具备的appendChild功能:)
答
document.getElementById(...)
将返回null
,如果它不能找到一个元素与给定的ID。
// You need to change:
var theRightSide = document.getElementById("rightside");
// To:
var theRightSide = document.getElementById("rightSide");
//^See capital 'S'
特别看到我的答案,第一个原因:http://*.com/a/14028960/218196。 –