在這段代碼中,當我調用cleanGrid()函數時,我的目標是擺脫類「circle」的div,並用類「square」替換爲div。對於我真的使用這段代碼來說他們不是可替換的項目,所以replaceChild()將不起作用。如果我將cleanGrid()的函數調用註釋掉,代碼運行良好,並且按鈕只是爲每次單擊添加一個帶有「square」類的div。我想要實際發生的是爲了cleanGrid()去除'grid'div中的任何內容,並且在調用此函數之後爲應該添加的任何內容留出空間 - 但是在調用此函數之後不會添加任何東西,並且我不知道爲什麼。爲什麼removeChild()阻止我在Javascript函數中執行appendChild()?
<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>