Correction status:qualified
Teacher's comments:案例举的不错
1.事件委托, 父元素代理了子元素上的事件, 或者说是子元素委托父元素来触发它上面的事件。事件委托必须要有冒泡。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>事件委托</title> </head> <body> <div> <ul> <li>item1</li> <li>item2</li> <li>item3</li> <li>item4</li> <li>item5</li> </ul> </div> <script> var lis = document.getElementsByTagName('li'); for ( var i = 0; i < lis.length; i++) { lis[i].addEventListener('click', function (ev) { alert('被点击了'); }, false); } var ul = document.getElementsByTagName('ul').item(0); ul.addEventListener('click', function (ev) { alert('被点击了'); ev.currentTarget; ev.target; }, false); </script> </body> </html>
点击 "运行实例" 按钮查看在线实例
运行图如下:
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>DOM操作: 删除留言</title> <style> .label { width: 100px; height: 50px; background-color: lavender; border: 1px solid black; text-align: center; margin: 10px auto 10px 0px; border-radius: 10px ; text-decoration-color: blueviolet; } #comment { width: 1000px; height: 50px; margin: 10px auto 10px 0px; border: #444444 1px solid; border-radius: 20px; background-color: lavender; } </style> </head> <body> <div class="label"> <label for="comment">请留言:</label> </div> <h3> <input type="text" id="comment" autofocus> </h3> <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); } return false; } </script> </body> </html>
点击 "运行实例" 按钮查看在线实例
运行图如下: