http://www.cnblogs.com/liugang-vip/p/5616484.html 不是抄的,这篇文章写的细
这是js 事件委托写法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>事件获取目标元素</title> <style> li{width: 499px;height: 50px;border: 1px solid #000;} ul{height: 300px;} </style> </head> <body> <ul id="ul1"> <li>a</li> <li>2</li> <li>3</li> <li>4</li> </ul> </body> <script> var lis = document.getElementsByTagName("li"); var ul1 = document.getElementById("ul1"); ul1.onclick = function(e){ var events = e || event; var target = e.target || e.srcElement; console.log(events.target.nodeName) } </script> </html>
下面是jQuery 写法:(用on)
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>事件获取目标元素</title> 6 <style> 7 li{width: 499px;height: 50px;border: 1px solid #000;} 8 ul{height: 300px;} 9 </style> 10 </head> 11 <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> 12 <body> 13 <ul id="ul1"> 14 <li>a</li> 15 <li>2</li> 16 <li>3</li> 17 <li>4</li> 18 </ul> 19 </body> 20 <script> 21 // var lis = document.getElementsByTagName("li"); 22 // var ul1 = document.getElementById("ul1"); 23 // ul1.onclick = function(e){ 24 // var events = e || event; 25 // var target = e.target || e.srcElement; 26 // console.log(events.target.nodeName) 27 // } 28 $('#ul1').on('click','li',function(){ 29 $(this).css('background','red') 30 }) 31 </script> 32 </html>