gpt4 book ai didi

javascript - 试图删除子元素的最后一个子元素

转载 作者:行者123 更新时间:2023-11-29 15:28:08 25 4
gpt4 key购买 nike

尝试删除“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>

最佳答案

您需要使用 removeChildlastElementChild,如下所示:

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

关于javascript - 试图删除子元素的最后一个子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37227648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com