在这段代码中,当我调用cleanGrid()函数时,我的目标是摆脱类'circle'的div并将其替换为带有'square'类的div。对于我真正使用此代码的内容,它们不是可替换的项目,因此replaceChild()不起作用。如果我注释掉对cleanGrid()的函数调用,代码运行正常,按钮只是为每次单击添加一个带有'square'类的div。我想要实际发生的是cleanGrid()删除'grid'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>
答案 0 :(得分:2)
我认为你的cleanGrid
函数不会像你编码的那样工作。即使x.childNodes
为空(NodeList
也不是假的),removeChild
仍将继续保持真实。所以我怀疑它抛出一个异常(在cleanGrid
调用上)或无休止地循环,这(无论哪种方式)是其他代码没有运行的原因。尝试在调试环境(Firefox + Firebug,IE + Visual Studio或开发工具包,无论如何)中运行它,在那里你可以看到发生了什么。
这是function cleanGrid() {
var x = document.getElementById("grid");
while (x.lastChild) {
x.removeChild(x.lastChild);
}
}
:
function cleanGrid() {
document.getElementById("grid").innerHTML = "";
}
或者,当然:
innerHTML
...因为{{1}}虽然不是标准的,但是得到了所有主要浏览器和大多数次要浏览器的支持。
答案 1 :(得分:0)
T.J。克劳德用行为背后的逻辑把它钉死了
然而,这将有效:
function cleanGrid() {
var x = document.getElementById("grid");
var len =x.childNodes.length;
while(len) {
x.removeChild(x.lastChild);
--len;
}
}