批改状态:合格
老师批语:
案例:经典的toDoList

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>作业:经典的toDoList</title><style>* {margin: 0;padding: 0;}body {background-color: rgb(235, 232, 232);}form {padding: 1em 1em;}ul li {padding: 1em 1em;border-bottom: 1px solid #f6f6f6;}</style></head><body><form action="" onsubmit="return false"><label for="comment">请留言:</label><input type="text" id="comment" name="comment" placeholder="回车确认" /></form><ul id="list"></ul><script>// 获取元素const comment = document.querySelector("#comment");const list = document.querySelector("#list");// 给文本框添加事件,回车确认// keyup: 键抬起时触发, keydown: 按下时触发comment.addEventListener("keyup", show, false);// show()函数function show(ev) {console.log(ev.key);if (ev.key === "Enter") {// 非空判断console.log(comment.value);if (comment.value.trim().length === 0) {alert("不能为空");comment.focus();return false;}// 通过了非空验证,说明用户输入了有意义的内容const li = document.createElement("li");li.innerHTML =comment.value + ' <button onclick="del(this)">删除</button>';// 将用户留言挂载/添加到ul中// list.appendChild(li);// 排序:最新留言在前面if (list.childElementCount === 0) {list.appendChild(li);} else {list.insertBefore(li, list.firstElementChild);}// 清空输入框comment.value = null;}}// 执行删除留言的操作function del(ele) {console.log(ele);// 要删除的是button的父元素liif (confirm("是否删除")) list.removeChild(ele.parentNode);}</script></body></html>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号