在这段代码中,当我调用 cleanGrid() 函数时,我的目标是摆脱“circle”类的 div,并将其替换为“square”类的 div。对于我真正使用此代码的原因,它们不是可替换的项目,因此 replaceChild() 不起作用。如果我注释掉对 cleanGrid() 的函数调用,则代码运行良好,并且该按钮只会为每次单击添加一个带有“square”类的 div。我想要实际发生的是 cleanGrid() 删除“网格”div中的任何内容,并为调用此函数后应添加的任何内容留出空间-但在调用此函数后无法添加任何内容,我不知道为什么。
<body>
<div id="grid"><div class="circle">hello</div></div>
<button onclick="addSquare()">add a Square</button>
<script language="JavaScript">
var g = {};
g.myGrid = document.getElementById("grid");
function addSquare() {
// Calling cleanGrid() is giving me problems.
// I want to wipe everything clean first and then add the divs of the 'square' class.
// But instead it just clears the 'grid' div and doesn't allow anything to be added.
cleanGrid(); // WHY NOT?
var newSquare = document.createElement("div");
newSquare.className = "square";
newSquare.innerHTML = "square";
g.myGrid.appendChild(newSquare);
}
function cleanGrid() {
var x = document.getElementById("grid");
while(x.childNodes) {
var o = x.lastChild;
x.removeChild(o);
}
}
</script>
</body>