Correction status:qualified
Teacher's comments:写得不错, 初学,建议在代码中多写点注释
1. 实例演示你对事件代理机制的理解?
事件委托是利用事件的冒泡原理来实现的,就是事件从最深的节点开始,然后逐步向上传播事件,只指定一个事件处理程序,就可以管理某一类型的所有事件。举例:div>ul>li,给li添加click事件,执行顺序li>ul>div
2.模仿留言板案例,
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>留言板</title> </head> <body> <h3>留言板</h3> <label for="comment">请留言:</label> <input type="text" id="comment" placeholder="请输入留言内容后按回车" autofocus> <ul id="list"></ul> <script> var comment = document.getElementById('comment'); var list = document.getElementById('list'); comment.addEventListener('keypress', addComment1, false); function addComment1(event) { if (event.key === 'Enter') { var item = document.createElement('li'); item.innerHTML = comment.value + ' <button>删除</button>'; if (list.childElementCount === 0) { list.appendChild(item); } else { list.insertBefore(item, list.firstElementChild); } comment.value = null; } } list.addEventListener('click', del, false); function del(event) { console.log(event.currentTarget); console.log(event.target); if (confirm('是否删除?')) { var ul = event.currentTarget; var btn = event.target; var li = btn.parentElement; ul.removeChild(li); } } </script> </body> </html>
点击 "运行实例" 按钮查看在线实例