1.实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> 一实例演示你对事件代理机制的理解</title> </head> <body> <div> <ul> <li>我</li> <li>是</li> <li>中</li> <li>国</li> <li>人</li> </ul> </div> <script> var lis = document.getElementsByTagName('li'); var ul = document.getElementsByTagName('ul').[0]; ul.addEventListener('click', function (event) { alert('被点击了'); event.currentTarget; event.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>作业简易留言板</title> </head> <body> <label for="comment">请留言:</label> <input type="text" id="comment" autofocus> <ul id="list"></ul> <script> var comment = document.getElementById('comment'); var list = document.getElementById('list'); comment.addEventListener('keypress', addComment1, false); function addComment1(evt) { if (evt.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(evt) { console.log(evt.currentTarget); console.log(evt.target); if (confirm('是否删除?')) { var ul = evt.currentTarget; var btn = evt.target; var li = btn.parentElement; ul.removeChild(li); } } </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例