1

我无法删除使用 JS 创建的对象的子对象的子对象。

基本上,一旦我创建了一个评论对象,我就会将Child(replyBox) 添加到它上面。在replyBox 中有一个取消按钮,它应该完全删除replyBox。

这是代码:

 function Comment(message){
    var self = this;
    var message = message;

    var comment = document.createElement("li");
    comment.id = "comment";
    comment.style = "display: none;";
    comment.textContent = message;

    createButtons(comment);

    var parent = document.getElementById("wall");
    parent.appendChild(comment);
    return comment;
}
function deleteComment(comment){
    var parent = document.getElementById("wall");
    parent.removeChild(comment);
}

function newReply(comment){
    var buttons = comment.getElementsByTagName("input");
    buttons.item(0).disabled="disabled";

    var replyBox = document.createElement("div");
    replyBox.id="replyBox";

    var replyTxt = document.createElement("input");
    replyTxt.type="text";
    replyTxt.value="Write a reply";
    replyTxt.onfocus = "if(this.value==this.defaultValue) this.value='';" ;
    replyTxt.onblur="if(this.value=='') this.value=this.defaultValue;";
    replyBox.appendChild(replyTxt);

    createButtons(replyBox);

    comment.appendChild(replyBox);  
}
function createButtons(parent){
    var button = document.createElement("input");
    button.type = "submit";
    if(parent.id=="comment"){
        var reply = button.cloneNode();
        reply.value = "reply";
        reply.addEventListener("click", function(){newReply(parent)},false);
        parent.appendChild(reply);

        var deleteBtn = button.cloneNode();
        deleteBtn.value = "delete";
        deleteBtn.addEventListener("click", function(){deleteComment(parent)},false);
        parent.appendChild(deleteBtn);
    }
    else{
        var submitBtn = button.cloneNode();
        submitBtn.value = "submit";
        //reply.addEventListener("click", function(){newReply(parent)},false);
        parent.appendChild(submitBtn);

        var cancel = button.cloneNode();
        cancel.value = "cancel";
        cancel.addEventListener("click", function(){cancel(parent)},false);
        parent.appendChild(cancel);
    }
}

function cancel(replyBox){
    replyBox.parentNode.removeChild(replyBox);
}
4

2 回答 2

2
   cancel.addEventListener("click", function(){cancel(parent)},false);

哪个cancel是哪个?您有一个被调用的对象cancel以及一个同名的函数。尝试重命名一个。

于 2010-12-19T06:09:54.717 回答
0

我在这里看到一个问题:

    comment.id = "comment";

如果您将评论元素的所有 ID 设置为comment,则 DOM 可能会变得混乱。

于 2010-12-19T06:11:59.973 回答