【发布时间】:2020-05-29 04:20:56
【问题描述】:
我可以让在我的 html 文件中创建的 li 在单击时被删除,但我无法让它动态创建的工作......任何建议将不胜感激!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To do</title>
<link rel="stylesheet" href="todo.css">
<script src="https://kit.fontawesome.com/ff289d152e.js" crossorigin="anonymous">
</script>
</head>
<body>
<div class="container">
<h1>To be done</h1>
<input id="add-todo" type="text" placeholder="What do you have to do?">
<ol id="tasks">
<li>
This one works <i class="fas fa-trash-alt"></i>
</li>
</ol>
</div>
<script type="text/javascript" src="todo.js"></script>
</body>
</html>
html {
box-sizing: border-box;
height: 100vh;
width: 100vw;
}
body{
font-family: 'Raleway';
background: url(https://i.gyazo.com/9024e4cc2d29408dd08bd67a54b355c8.png);
background-size: cover;
background-position: center;
display: flex;
justify-content: center;
align-items: center;
position: absolute;
width: 100%;
height: 100%;
}
.container {
display: flex;
flex-direction: column;
background-color: gray;
margin: 10px;
padding: 10px;
}
单击时添加此样式...
.completed {
text-decoration: line-through;
}
i {
margin-left: 20px;
}
let addTaskField = document.getElementById('add-todo');
let tasks = document.getElementById('tasks');
let todos = document.querySelectorAll("li");
// create a todo
addTaskField.addEventListener('keypress', function(event){
if(event.which === 13 && this.value != ''){
let li = document.createElement("li");
let i = document.createElement("i");
i.classList = "fas fa-trash-alt";
li.innerHTML = this.value;
li.appendChild(i);
tasks.append(li);
this.value = '';
}
});
我不能只选择所有 lis,即使它们是稍后创建的,然后循环通过它们添加事件侦听器吗?
// add strikethrough
todos.forEach(function(todo) {
todo.addEventListener('click', function() {
this.classList.toggle('completed');
});
})
【问题讨论】:
标签: javascript html strikethrough