主题
待办事项清单
待办事项清单(To-Do List)是经典的入门级项目,有助于加深对 jQuery 增删改 DOM、事件处理等核心功能的理解。
功能目标
- 添加待办事项
- 点击标记完成
- 删除事项
- 保持交互流畅、简洁美观
HTML 结构示例
html
<div id="todoApp">
<input type="text" id="todoInput" placeholder="请输入任务..." />
<button id="addBtn">添加</button>
<ul id="todoList"></ul>
</div>
jQuery 实现逻辑
js
$(function () {
$("#addBtn").click(function () {
const text = $("#todoInput").val().trim();
if (!text) return alert("请输入任务内容");
$("#todoList").append(
`<li><span class="task">${text}</span><button class="del">删除</button></li>`
);
$("#todoInput").val("");
});
// 事件委托绑定删除
$("#todoList").on("click", ".del", function () {
$(this).parent().remove();
});
// 点击标记完成
$("#todoList").on("click", ".task", function () {
$(this).toggleClass("done");
});
});
CSS 样式建议
css
#todoApp {
width: 300px;
margin: 20px auto;
}
#todoInput {
width: 200px;
padding: 5px;
}
#addBtn {
padding: 6px 10px;
}
#todoList {
list-style: none;
padding: 0;
margin-top: 10px;
}
#todoList li {
padding: 6px;
background: #f2f2f2;
margin-bottom: 5px;
display: flex;
justify-content: space-between;
align-items: center;
}
.task.done {
text-decoration: line-through;
color: gray;
}
.del {
background: red;
color: white;
border: none;
padding: 3px 6px;
cursor: pointer;
}
完整示例代码
loading