复选框在单击checkBox以查看待办事项列表时如何删除文本

时间:2016-12-19 12:16:14

标签: javascript html

我正在尝试在单击文本旁边的复选框时删除文本,由于某种原因,它只是跨越了所有下一个元素,即使我只点击了一个。我正在使用事件处理程序,但由于某种原因它不起作用。很感谢任何形式的帮助。感谢

function myFunction() {
    var item = document.getElementById("todoInput").value
    var checkBox = document.createElement("input");
    checkBox.type = "checkbox";
    checkBox.id = "checkbox"
    checkBox.onclick = updateItem
    var text = document.createTextNode(item)
    var newItem = document.createElement("li")
    newItem.className = "addedClass"
    newItem.appendChild(text)
    if (item === "") {
        alert("please fill in the blanks");
    } else {
        var crap = document.getElementById("todoList")
        crap.appendChild(newItem)
        var addhere = document.getElementById("todoList")
        addhere.appendChild(checkBox);
    }

    function updateItem() {
        if (document.getElementById("checkbox").checked) {
            document.getElementById("todoList").style.textDecoration = "line-through"
        }
    }
}
<form name="myForm" id="todoForm">
    <input id="todoInput" name="fname" required>
    <button type="button" onclick="myFunction()">OK</button>
</form>
<ol id="todoList"></ol>

2 个答案:

答案 0 :(得分:0)

你可以用简单的HTML / CSS做到这一点,不需要JS:

(更新了示例,删除了多余的代码)

ol li del {
text-decoration: none;
}
ol li input[type=checkbox]:checked ~ del {
text-decoration: line-through;
}
<ol>
  <li><input type="checkbox"><del>This is a list-item</del></li>
</ol>

答案 1 :(得分:0)

每次添加新列表项时,您可能需要绑定到新条目的新点击处理程序:

checkBox.onclick = updateItem.bind(checkBox);

完整代码:

function myFunction() {
  var item = document.getElementById("todoInput").value;
  if (item === "") {
    alert("please fill in the blanks");
  } else {
    var text = document.createTextNode(item);
    var newItem = document.createElement("li");
    var crap = document.getElementById("todoList");
    crap.appendChild(newItem);
    var checkBox = document.createElement("input");
    checkBox.type = "checkbox";
    checkBox.onclick = updateItem.bind(checkBox);
    newItem.appendChild(checkBox);
    newItem.appendChild(text);
    document.getElementById("todoInput").value = "";
    checkBox.className = "addedClass";
  }

  function updateItem() {
    if (this.checked) {
      this.parentNode.style.textDecoration = "line-through";
    } else {
      this.parentNode.style.textDecoration = "none";
    }
  }
}
<form name="myForm" id="todoForm">
  <input id="todoInput" name="fname" required>
  <button type="button" onclick="myFunction()">OK</button>
</form>
<ol id="todoList"></ol>