<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>事件委託</title> <style> ul{ padding: 20px; list-style: none; } </style> </head> <body> <ul id="ul"> <li>111</li> <li>222</li> <li>333</li> <li>444</li> </ul> <script> var ul = document.getElementById('ul'); ul.onmouseover = function (ev) { var ev = ev || window.event, target = ev.target || ev.srcElement; //獲取事件源 if (target.nodeName.toLowerCase() == "li") { target.style.background = "red"; } } ul.onmouseout = function (ev) { var ev = ev || window.event, target = ev.target || ev.srcElement; if (target.nodeName.toLowerCase() == "li") { target.style.background = ""; } } </script> </body> </html>
事件委託:利用事件冒泡的原理,把事件添加到父級或祖先元素上,來觸發執行效果.html
好處:node
1.提升性能.性能
2.將來添加進來的元素,身上依然能觸發事件.spa