我正在尝试使用JavaScript制作一个简单的待办事项列表。基本上,您在输入字段中输入一个项目,它会被添加到列表中,如果它完成则单击它,然后它会被越过。如果单击已经划掉的列表,则会删除该行。但是删除一条线路时,添加直通线是行不通的。
HTML:
<div><input type="text" value="" id="new_task"><button id="add_task">Add Task</button></div>
<ul id="tasks">
<li class="completed selected">One Task</li>
<li>Two Task</li>
</ul>
CSS:
<style type="text/css" media="screen">
/*local styles if any (quick tests and local only overrides)*/
#tasks li{
list-style: none;
}
#tasks .selected{
list-style: disc;
}
.completed{
text-decoration: line-through;
}
</style>
JavaScript的:
<script type="text/javascript" charset="utf-8">
var inputField = document.querySelector("#new_task");
var myButton = document.querySelector("#add_task");
var taskList = document.querySelector("#tasks");
var newList = document.createElement("li");
var completeTask = document.querySelector("li.completed.selected");
var incompleteTask = document.querySelector("li:not([class])");
myButton.onclick = function() {
taskList.appendChild(newList);
newList.innerHTML = inputField.value;
inputField.value = "";
}
completeTask.onclick = function() {
event.target.classList.remove("completed","selected");
}
incompleteTask.onclick = function() {
event.target.classList.add("completed","selected");
}
</script>
答案 0 :(得分:3)
答案 1 :(得分:1)
脚本仅解析文档一次,document.querySelector("li.completed.selected")
返回一个节点。因此,删除这些类仅适用于 One Task ,它在解析脚本时具有这些类。
您需要手动为每个创建的项目添加onclick
处理程序,请参阅jsFiddle。
var inputField = document.querySelector("#new_task");
var myButton = document.querySelector("#add_task");
var taskList = document.querySelector("#tasks");
var lis = document.querySelectorAll("#tasks li");
function clickHandler() {
if(event.target.classList.contains("completed"))
event.target.classList.remove("completed","selected");
else
event.target.classList.add("completed","selected");
}
// add onclick handler to existing nodes
for(var i=0; i<lis.length; ++i) lis[i].onclick = clickHandler;
myButton.onclick = function() {
var newList = document.createElement("li");
taskList.appendChild(newList);
newList.innerHTML = inputField.value;
inputField.value = "";
// add onclick handler to new nodes
newList.onclick = clickHandler;
}