Uncaught TypeError: Cannot read property 'lastChild' of null

后端 未结 1 1562
我寻月下人不归
我寻月下人不归 2021-01-15 00:14



        
相关标签:
1条回答
  • 2021-01-15 00:52

    You are trying to access the element with id leftSide before it has been added to the DOM.

    If you move your script to the end of the page body, you will no longer see this error, but a different, unrelated one instead:

    <!DOCTYPE html>
    <html>
    <head>
    	<title>Face Matching Game</title>
    	<h2>Matching Game</h2>
    	<p>Click on the EXTRA face on the left side</p>
    	<style type="text/css">
    		div { position: absolute; width: 640px; height: 550px; background-color: maroon }
    		img { position: absolute; width: 100px; height: 100px}
    		#rightSide { left: 650px; border-left: 2px solid black; }
    	</style>
     
    </head>
    <body onload="generateFaces()">
    	<div id="leftSide"></div>
    	<div id="rightSide"></div>
    
       	    <script type="text/javascript">
    		var NUM_OF_FACES = 0;
    		var THE_LEFT_SIDE, THE_RIGHT_SIDE;
    		//Function to generate faces
    		function generateFaces() {
    			THE_LEFT_SIDE = document.getElementById("leftSide");
    			THE_RIGHT_SIDE = document.getElementById("rightSide");
    			NUM_OF_FACES += 5;
    			var image;
    			while(NUM_OF_FACES>0){
    				image = document.createElement("img");
    				image.src = "smile.png";
    				image.style.top = Math.floor(Math.random()* (THE_LEFT_SIDE.offsetHeight - 100)) + "px";
    				image.style.left = Math.floor(Math.random()* (THE_LEFT_SIDE.offsetWidth - 100)) + "px";
    				THE_LEFT_SIDE.appendChild(image);
    				NUM_OF_FACES -= 1;
    				//console.log(image.style.top, image.style.left )
    			}
    			var leftSideImages = THE_LEFT_SIDE.cloneNode(true);
    			leftSideImages.removeChild(leftSideImages.lastChild);
    			THE_RIGHT_SIDE.appendChild(leftSideImages);
    		}//end generatefaces()
    
    		function deleteFaces(argument) {
    			while(THE_LEFT_SIDE.firstChild){
    				THE_LEFT_SIDE.removeChild(THE_LEFT_SIDE.firstChild);
    			}
    			while(THE_RIGHT_SIDE.firstChild){
    				THE_RIGHT_SIDE.removeChild(THE_RIGHT_SIDE.firstChild);
    			}
    		}//end deleteFaces()
    
    		var theBody = document.getElementsByTagName("body")[0];
    		THE_LEFT_SIDE = document.getElementById("leftSide");
    		THE_RIGHT_SIDE = document.getElementById("rightSide");
    		//Event handling
    		THE_LEFT_SIDE.lastChild.onclick = function goToNextLevel() {
    			alert("You clicked on correct face.");
    			deleteFaces();
    			generatefaces();
    		};
    		theBody.onclick = function gameOver() {
    			alert("Game Over!!");
    			theBody.onclick = null;
    			THE_LEFT_SIDE.lastChild.onclick = null;
    		};
    	</script>
    </body>
    </html>

    0 讨论(0)
提交回复
热议问题