我正在尝试删除子元素,但我一直找不到错误节点

时间:2018-01-18 07:16:49

标签: javascript

我对编码很新,所以我不确定你是否能全面了解这一点,但如果这还不够,我可以澄清一下。非常感谢任何帮助。谢谢!

 //remove and complete svg format
 var removeSVG = '<svg></svg>';
 var completeSVG = '<svg></svg>';


 //user clicked on the add button
 //If there is any text in the input field add that to the Todo list
document.getElementById('add').addEventListener('click', function () {
var value = document.getElementById('item').value;
if (value) {
    addItemTodo(value);
    document.getElementById('item').value = "";
}

});

function deleteItem() {
var item = this.parentNode.parentNode;
var parent = this.parentNode;

parent.removeChild(item);
}

function completeItem() {
var item = this.parentNode.parentNode;
var parent = this.parentNode;
var id = parent.id;

var target = (id === 'todo') ? document.getElementById('completed') : document.getElementById('todo');

parent.removeChild(item);
target.insertBefore(item, target.childNodes[0]);
}


//Adds a new item to the todo list
function addItemTodo(text) {

var list = document.getElementById('todo');

var item = document.createElement('li');
item.innerText = text;

var buttons = document.createElement('div');
buttons.classList.add('buttons');

var remove = document.createElement('button');
remove.classList.add('remove');
remove.innerHTML = removeSVG;

//add click event for remove button
remove.addEventListener('click', deleteItem);

var complete = document.createElement('button');
complete.classList.add('complete');
complete.innerHTML = completeSVG;

//add click event for the complete button
complete.addEventListener('click', completeItem);

buttons.appendChild(remove);
buttons.appendChild(complete);
item.appendChild(buttons);
list.insertBefore(item, list.childNodes[0]);

}

  //add click event for remove button
remove.addEventListener('click', deleteItem);

所以我发布了整个javascript,所以你对结构有所了解,html本身就是两个id = todo并分别完成的标签

2 个答案:

答案 0 :(得分:1)

检查此https://jsfiddle.net/dp722j27/

function deleteItem() {
    var parent = this.parentNode.parentNode.parentNode;
    var item = this.parentNode.parentNode;
    parent.removeChild(item);
}

答案 1 :(得分:0)

如果要删除已单击的按钮,请执行以下操作:

function deleteItem(event) {
  var item = event.target.parentNode;
  var parent = event.target.parentNode.parentNode;
  parent.removeChild(item);
}

  //add click event for remove button
document.addEventListener('click', deleteItem);