我是编程和乐趣的新手,我试图整理一个待办事项列表应用程序。
当用户点击第一个项目的文本时,程序将浏览文本,当用户单击第一个项目上的复选框时,它会像我想要的那样消失。但是当我添加新任务时,删除和复选框都不起作用。这是我的代码。谢谢。
HTML
<!DOCTYPE html>
<head>
</head>
<body>
<div id = "header">
<h1> To Do List</h1>
</div>
<div id = "form">
<form>
<input type = "text" id = "todo">
<button type = "button" id= "submit"> Submit </button>
</form>
</div>
<div id = "tasklist">
<ol id = "list">
<li id = "listitem"><input type = "checkbox" class="checkbox"
> Clean</li>
</ol>
</div>
<script type="text/javascript" src="todo.js"></script>
</body>
这是我的js
window.onload = function(){
//Add new to do task by entering text and clicking submit
var submit = document.getElementById('submit');
submit.onclick = function(){
var task = document.getElementById('todo').value;
console.log(task);
var ol = document.getElementById("list")
var entry = document.createElement('li');
entry.id = 'id'
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.className = "checkbox"
entry.appendChild(checkbox)
entry.appendChild(document.createTextNode(task));
ol.appendChild(entry);
};
//Strike through task if click on text
$("li").click(function(){
$(this).css("text-decoration", "line-through");
});
//Remove task when click checkbox
$(".checkbox").click(function(){
$(this).parent().hide();
})
};
答案 0 :(得分:1)
$("li").click(function(){
单击处理程序仅适用于应用处理程序时DOM中的元素 - 它不适用于将来的元素!您需要实现jQuery的.on()
处理程序,将用于将来添加到DOM的元素。
//Strike through task if click on text
$(document).on('click','li', function(){
$(this).css("text-decoration", "line-through");
});
//Remove task when click checkbox
$(document).on('change','.checkbox', function(){
$(this).parent().hide();
});
答案 1 :(得分:0)
您需要为这些链接委派事件处理程序,因为在呈现页面时它们不在DOM中。您可以通过使用click
附加$(document).on()
处理程序并指定希望处理程序附加到的元素来执行此操作。
以下是参考https://learn.jquery.com/events/event-delegation/
//Add new to do task by entering text and clicking submit
var submit = document.getElementById('submit');
submit.onclick = function() {
var task = document.getElementById('todo').value;
console.log(task);
var ol = document.getElementById("list")
var entry = document.createElement('li');
entry.id = 'id'
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.className = "checkbox"
entry.appendChild(checkbox)
entry.appendChild(document.createTextNode(task));
ol.appendChild(entry);
};
$(document).on('click', 'li', function(e) {
//Strike through task if click on text
$(this).css("text-decoration", "line-through");
}).on('click', '.checkbox', function(e) {
//Remove task when click checkbox
$(this).parent().hide();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header">
<h1> To Do List</h1>
</div>
<div id="form">
<form>
<input type="text" id="todo">
<button type="button" id="submit"> Submit </button>
</form>
</div>
<div id="tasklist">
<ol id="list">
<li id="listitem"><input type="checkbox" class="checkbox"> Clean</li>
</ol>
</div>