用普通的javascript无法读取null错误的属性'parentNode'

时间:2017-03-06 21:11:54

标签: javascript

我正在通过javascript创建新元素并将其附加到已存在的div:

function addElement(){
    var dodato = document.getElementById('dodato');
    var input = document.getElementById('input');
    if(input.value!==""){
        var div = document.createElement('div');
        dodato.appendChild(div);
        var ele = dodato.lastChild;
        ele.style.width = "200px";
        ele.style.float = "left";
        ele.innerHTML = input.value;
        ele.id = input.value;
        var deletE = document.createElement('span');
        ele.appendChild(deletE);
        var deletEe = ele.lastChild;
        deletEe.innerHTML = 'X';
        deletEe.style.color = "red";
        deletEe.style.float = 'right';
        deletEe.setAttribute('onclick','deleteE('+input.value+')');
    }
}

dodato是div,我添加了所有新元素,所有这些元素都有不同id

通过单击span我调用new函数来删除一些具有特定id的添加元素。

function deleteE(delete_value){
    var dodato = document.getElementById('dodato');
    var el = document.getElementById(delete_value);
    dodato.removeChild(el);
}

我不断得到的错误是:

无法在'Node'上执行'removeChild':参数1不是'Node'类型。

dodato.removeChild(el);

1 个答案:

答案 0 :(得分:1)

在您的第一个代码段中,您说

deletEe.setAttribute('onclick','deleteE('+input.value+')');

然后在deleteE中你说:

var el = document.getElementById(delete_value);

因此,您尝试使用获取elementById,而不是 id 。改变

deletEe.setAttribute('onclick','deleteE('+input.value+')');

deletEe.setAttribute('onclick','deleteE('+input.id+')');