事件委托示例
代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button id="add">添加</button> <ul id="list"> <li>11</li> <li>22</li> <li>33</li> </ul> <script> var lis = document.getElementsByTagName('li'); var add = document.getElementById('add'); // for(var i=0;i<lis.length;i++){ // 0 1 2 // lis[i].index = i; // lis[i].onclick = function(){ // alert(this.index); // } // } add.onclick = function(){ var newLi = document.createElement('li'); newLi.innerHTML = 'ccc'; list.appendChild(newLi); } list.onclick = function(ev){ // 将事件委托给父元素 ul,由ul来分配给子元素 var eve = event || ev; console.log(eve.target); eve.target.style.background = 'pink'; } </script> </body> </html>