2015-11-07 56 views
1

。這是我的代碼,我在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); 
 
    }; 
 
}

當我使用theRightSide.appendChild(theLeftimages)附加子

; 它顯示一個錯誤

Uncaught TypeError: Cannot read property 'appendChild' of null.

,我不能克隆圖像右側股利。

+0

特別看到我的答案,第一個原因:http://stackoverflow.com/a/14028960/218196。 –

回答

0

JavaScript是區分大小寫的。它應該是rightSide

var theRightSide = document.getElementById("rightSide"); 

由於沒有得到的元素,它返回NULL以theRightSide,這顯然不具備的appendChild功能:)

0

document.getElementById(...)將返回null,如果它不能找到一個元素與給定的ID。

// You need to change: 
var theRightSide = document.getElementById("rightside"); 
// To: 
var theRightSide = document.getElementById("rightSide"); 
               //^See capital 'S'