删除子节点

时间:2016-09-08 09:27:34

标签: javascript jquery

当我单击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;
        }   
    }

1 个答案:

答案 0 :(得分:0)

我发现,我实际上是移除所有身体元素而不是左右两侧。这很有意义。所以我用

替换 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();
        };