2016-05-14 117 views
3

尝试移除“leftSideImages”的最后一个子元素,使右侧的图像少于左侧的图像。以下是我的代码。目标是将左侧的图像克隆到右侧减去一个。谢谢!试图移除子元素的最后一个子元素

<!DOCTYPE html> 
<html> 
    <head> 
    <meta charset="utf-8"> 
    <title>Matching Game</title> 
    <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 = 0; i< numberOfFaces; i++){ 
       var random_top = Math.floor(Math.random() * 400); 
       var random_left = Math.floor(Math.random() * 400); 

       var img = document.createElement("img"); 
       img.src="smile.png"; 
       img.style.top = random_top + "px"; 
       img.style.left = random_left + "px"; 


       theLeftSide.appendChild(img); 

      } 
      var leftSideImages = theLeftSide.cloneNode(true); 
      //this doesn't work   leftSideImages.removeChild(theLeftSide.lastChild); 
      // it gets rid of everything. 
      // I'm trying to clone the left side onto the right with one less image 
      theRightSide.appendChild(leftSideImages); 
     } 
    </script> 
    </head> 
    <body> 
     <h3>Matching Game</h3> 
     <p>Click on the extra smiling face on the left.</p> 
     <div id="leftSide"></div> 
     <div id="rightSide"></div> 
     <script>generateFaces()</script> 
    </body> 
</html> 
+0

'theLeftSide.lastChild'不是'leftSideImages'的孩子,它是'theLeftSide'的孩子。 – Barmar

+0

当你克隆'theLeftSide'时,你也克隆了所有的孩子,因为你说'deep = true'。 – Barmar

+0

只是为了澄清。我想保持左侧完好无损。我只想删除右侧的一个图像。最后一个。谢谢。 – martinbshp

回答

0

您需要使用removeChild之lastElementChild,像这样:

var parent = document.getElementById("leftSide"); 
 
parent.removeChild(parent.lastElementChild);
<div id="leftSide"> 
 
    <div>1</div> 
 
    <div>2</div> 
 
    <div>3</div> 
 
</div>

+0

感谢Hors帮助。 – martinbshp

0

您正在尝试删除一个不同元素的孩子一个比你打电话removeChild。它应该是:

leftSideImages.removeChild(leftSideImages.lastChild); 

我不确定为什么你的代码删除了所有内容。根据文档,如果参数不是给定父项的子项,它应该抛出异常。

0

的原因是你是克隆整个左侧,然后删除最后一个孩子这是整个左侧,

var leftSideImages = theLeftSide.cloneNode(true); 
    //leftSideImages now has whole theLeftSide - the div not its content. 

    var i,l, children; 
    children = theLeftSide.childNodes; 
    i=0; 
    l = children.length; 

    for(i; i< l ; i++){ 
    theRightSide.appendChild(children[i].cloneNode(true)); 
    } 

    theRightSide.removeChild(theRightSide.lastChild); 

请注意,你可能是更好的解决方案。

这里是小提示向你展示它的工作原理。

https://jsfiddle.net/f0hrre90/

+0

将解决方案放在答案中,而不仅仅是小提琴。 – Barmar

+0

当然可以。完成 - 小提琴只是表现得更好。 –

+0

为什么放弃投票 –

0

使用leftSideImages.removeChild(leftSideImages.lastChild); 而不是leftSideImages.removeChild(theLeftSide.lastChild);

这是已经给予其中一位朋友的正确答案。 :-) 另外我在我的机器上运行相同的东西。