2016-09-08 57 views
0

我能夠成功地刪除所有的子節點,當我點擊leftSide的lastChild,但無法使用遞增的numberOfFaces再次運行函數generateFaces()本身。刪除子節點後,我無法重新運行該功能

var numberOfFaces = 5; 

    function generateFaces() { 

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

     var theBody = document.getElementsByTagName("body")[0]; 

     while(numberOfFaces > 0) { 
      // CREATING IMG ELEMENTS AND APPENDING THEM TO THE LEFTSIDE DIV 
      var img = document.createElement("img"); 
      img.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png" ; 
      img.style.top = Math.floor(Math.random() * 400) +"px"; 
      img.style.left = Math.floor(Math.random() * 400) +"px"; 
      theLeftSide.appendChild(img); 

      // CLONING THE LEFT SIDE DIV ELEMENTS, REMOVING THE LAST CHILD AND APPENDING THEM TO THE RIGHT CHILD 
      var leftSideImages = theLeftSide.cloneNode(true); 
      leftSideImages.removeChild(leftSideImages.lastChild); 
      theRightSide.appendChild(leftSideImages); 
      numberOfFaces--; 
     } 

     theLeftSide.lastChild.onclick = function nextLevel(event){ 
      while(theBody.firstChild) { 
       theBody.removeChild(theBody.firstChild); 
      } 
      event.stopPropagation(); 
      numberOfFaces += 5; 
      generateFaces(); 

     }; 

     theBody.onclick = function gameOver(event) { 
      alert("Game Over!"); 
      theBody.onclick = null; 
      theLeftSide.lastChild.onclick = null; 
     } 
    } 
+0

你爲什麼要刪除單擊事件? – madalinivascu

+0

我想我只是刪除所有的子節點。我害怕我不知道我在做什麼! –

+0

我想要做的是,我點擊左邊的最後一個孩子後。相同的函數必須再次運行numberOfFaces變量的增量。 –

回答

0

我發現,我實際上是刪除所有的身體元素,而不是左側和右側。它使我sense..so更換nextLevel功能與

theLeftSide.lastChild.addEventListener("click",function(e){nextLevel(e);}); 
     function nextLevel(e) 
     { 
      while (theLeftSide.firstChild) { 
       theLeftSide.removeChild(theLeftSide.firstChild); 
      } 
      while (theRightSide.firstChild) { 
       theRightSide.removeChild(theRightSide.firstChild); 
      }        
      numberOfFaces += 5;    
      generateFaces(); 
      e.stopPropagation(); 
     };