JavaScript removeChild帮助。

| 我正在编写一个简单的小段代码来绘制鼠标,无论鼠标在盒子的哪个位置。我也想有一个清除按钮。绘图工作正常,但我似乎无法使清除按钮正常工作。这是我的.js文件的相关部分:
function pixel(x, y) {
    var pix = document.createElement(\"div\");
    pix.setAttribute(\"style\", \"position:absolute;left:\" + x + \"px;top:\" +
        y + \"px;width:3px;height:3px;background:#000;cursor:crosshair\");
    return pix;
}

var mouseDown = false;

function draw(event) {
    if (!mouseDown) return;
    var x = event.clientX;
    var y = event.clientY;
    document.getElementById(\"box\").appendChild(pixel(x, y));
}

/* Neither 1, 2, nor 3 work! */
function clear() {
    var box = document.getElementById(\"box\");
    /* 1 */
    // box.innerHTML = \"\";
    /* 2 */
    // box.childNodes = new NodeList();
    /* 3 */
    for (n in box.childNodes)
        box.removeChild(n);
}
HTML文件的相关部分是:
<body onmousedown=\"mouseDown=true\" onmouseup=\"mouseDown=false\">
<div id=\"box\" onmouseover=\"document.getElementById(\'box\').style.cursor=\'crosshair\'\"
    onmousemove=\"draw(event)\"></div>
<button onclick=\"clear()\">Clear</button>
</body>
该框还使用CSS进行了格式化,但这不应该成为问题。我觉得问题可能出在我要从方框中删除像素,而不是从文档中删除像素或某些东西,但是我是JavaScript noob,所以我不知道。     
已邀请:
        将函数重命名为其他名称(不是clear())。
function removePixels() {
var box = document.getElementById(\"box\");

if (box.hasChildNodes() )
{
while ( box.childNodes.length >= 1 )
{
    box.removeChild( box.firstChild );       
} 
}

  }//end function
    
        我不认为ѭ3是函数的有效名称。 http://jsfiddle.net/zUJ2e/ 编辑:是的,绝对不是 http://www.roseindia.net/javascript/javascript-clear-method.shtml     
        您不应该在NodeList上使用\“ for ... in \”循环:
for (var n = 0; n < childNodes.length; ++n)
  box.removeChild(childNodes[n]);
NodeList不是数组,尽管有时它的行为类似于一个数组。通常,“ for ... in”用于对象,而不是数组。 另一个完全分开的注释:在某些浏览器中以这种方式设置“样式”(对于您的“像素”),可能会遇到问题。在所有浏览器中,DOM节点的\“ style \”属性都被视为不可思议的魔术,但是我的回忆是,做自己的事情不一定总能奏效。相反,您可以将各个属性设置为individual5ѭ。     
        您将按钮连接到事件处理程序的方式是无意中点击了document.clear(),而不是您定义的clear()函数。 避免这种情况的一种方法是将函数重命名为其他名称。例如,如果将函数重命名为myClear(),则应解决此特定冲突。但是,这确实有点狡猾。 您可以在JavaScript本身中绑定事件处理程序,这似乎更可靠。如果您使用的是JQuery库,则可以执行以下操作,例如:
// when the document is ready...
$(document).ready(function() {
    // connect all buttons to the clear event handler.
    $(\'button\').click(clear); 
})
如果您尝试使用原始JavaScript,则可以在DOM树准备就绪时在JavaScript中设置onclick属性。
<body onmousedown=\"mouseDown=true\" onmouseup=\"mouseDown=false\">
<div id=\"box\" onmouseover=\"document.getElementById(\'box\').style.cursor=\'crosshair\'\"
     onmousemove=\"draw(event)\"></div>
<!-- button has an id to make it selectable with getElementById() -->
<button id=\"button\">Clear</button>

<!-- Placed at the bottom so we have a chance of getting button -->
<script>
    document.getElementById(\"button\").onclick = clear;
</script>

</body>
    

要回复问题请先登录注册