如何使删除按钮和完成按钮在ToDO List Javascript上起作用

时间:2019-02-14 01:45:36

标签: javascript events

我正在用Javascript创建待办事项列表,但不确定如何使删除/完成按钮起作用。当我点击删除按钮时,我希望它删除li,而当我点击完整按钮时,我希望我的li背景变为背景#51DF70。到目前为止,当我按下删除/完成按钮时,它会提醒我,所以我知道它们正在工作

到目前为止,这是我的代码,如果有帮助,我的Codepen

var input = document.getElementById('userInput');
var enterButton = document.getElementById('enter');
var deleteButtons = document.getElementsByClassName("Remove");
for (var i = 0; i < deleteButtons.length; i++) {
  deleteButtons[i].addEventListener('click', deleteListItem, false);
}

var completeButtons =
  document.getElementsByClassName("Complete");
for (var i = 0; i < completeButtons.length; i++) {
  completeButtons[i].addEventListener('click', completeListItem, false);
}
var ul = document.querySelector('ul');

function inputLength() {
  return input.value.length;
};

function listLength() {
  return item.length;
}

function createListElement() {
  var li = document.createElement('li');
  li.appendChild(document.createTextNode(input.value));
  //makes text node 

  var clonedButton =
    document.getElementById("buttons").cloneNode(true);
  clonedButton.childNodes[1].addEventListener('click', deleteListItem, false);
  clonedButton.childNodes[3].addEventListener('click', completeListItem, false);

  li.appendChild(clonedButton);
  ul.appendChild(li);
  input.value = "";

}

function deleteListItem() {
  alert("Yuh");
  // li.classList.add("delete");
}

function completeListItem() {
  alert("Item was completed");
  li.classLi

}

function addListAfterClick() {
  if (inputLength() > 0) {
    createListElement();
  }
}
// Hit enter key and create list
function addAfterPress(event) {
  if (inputLength() > 0 && event.which === 13) {
    createListElement();
  }
}

enterButton.addEventListener('click', addListAfterClick);
input.addEventListener('keypress', addAfterPress);

1 个答案:

答案 0 :(得分:0)

li是删除和完成按钮的祖父母节点(父节点是buttons的克隆)。所以你想要:

function deleteListItem() {
  var li = this.parentNode.parentNode;
  li.remove();
}

function completeListItem() {
  var li = this.parentNode.parentNode;
  li.classList.add("Complete");
}