标签:
<!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>
事件委托:利用事件冒泡的原理,把事件添加到父级或祖先元素上,来触发执行效果.
好处:
1.提高性能.
2.未来添加进来的元素,身上依然能触发事件.
标签:
原文地址:http://www.cnblogs.com/stefan-47/p/5625172.html