我正在完成课程证书的评估。在我的最后一项任务中,我被要求创建一个迷你js游戏,它会在两个镜像面生成随机面,一面会丢失一个面。
在&#34; 缺少面部上方的onclick事件< / EM>&#34;应该触发我的函数 nextLevel(),它将删除两个div(镜像div)并生成新内容。
我已经开发了这个脚本以解决问题,但我对onclick
事件有一个特定的错误。它说:
未捕获的TypeError:无法设置属性&#39; onclick&#39;为null
但是运行一个DOM查看器,它表示在leftSide Div上添加了5个孩子。请帮助我,我无法找到解决这个问题的方法。
var numberOfFaces=5;
var theLeftSide=document.getElementById("leftSide");
var theRightSide=document.getElementById("rightSide");
var theBody =document.getElementsByTagName("body")[0];
function generateFaces(){
for(i=0;i<numberOfFaces;i++){
var oImg=document.createElement("img"); // Creates an oimg node
oImg.setAttribute('src', 'http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png'); // sets the source for img file
theLeftSide.appendChild(oImg); // append the img to leftSide Div.
oImg.style.top = Math.floor(Math.random()*401)+'px';
oImg.style.left = Math.floor(Math.random()*401)+'px';
}
copyDiv();
}
function copyDiv(){
var cloned = theLeftSide.cloneNode(true);
cloned.removeChild( cloned.childNodes[ cloned.childNodes.length - 1 ] );
theRightSide.appendChild(cloned);
}
theLeftSide.lastChild.onclick=function nextLevel(event){
event.stopPropagation();
numberOfFaces += 5;
deleteAllChilds();
generateFaces();
};
/*
theBody.onclick =function gameOver() {
alert("Game Over!");
theBody.onclick = null;
theLeftSide.lastChild.onclick = null;
};
*/
function deleteAllChilds(){
while(theLeftSide.childNodes.length>0){
theLeftSide.removeChild(theLeftSide.childNodes[theLeftSide.childNodes.lenth-1]);
}
while(theRightSide.childNodes.length>0){
theRightSide.removeChild(theRightSide.childNodes[theRightSide.childNodes.lenth-1]);
}
}
答案 0 :(得分:0)
一般来说
当您尝试在尚未加载的DOM对象上应用事件时,未捕获的TypeError:无法设置属性&#39; onclick&#39;为null
会被警告!为了避免这种情况,请确认您的脚本已加载到<head>
元素中,或者它是否在正文中,请确保在HTML内容为id&#34; leftSide&#34;之前加载它。 ..
答案 1 :(得分:0)
这是函数nextLevel的位置。在函数generateFaces中添加它将提供我正在寻找的可用性。谢谢大家。