简单的事件委托
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Document</title>
6 </head>
7 <body>
8 <input type="button" value="添加" id="btn1">
9 <ul id="ul1">
10 <li>0001</li>
11 <li>0002</li>
12 <li>0003</li>
13 <li>0004</li>
14 </ul>
15 <script>
16 //優(yōu)點(diǎn):性能高;新添加的元素依然會(huì)擁有事件
17
18 //事件委托:利用冒泡的原理,把事件加到父級(jí)上
19 //事件源:不管在哪個(gè)事件中,只要你操作的哪個(gè)元素就是事件源
20 var oUl = document.getElementById("ul1");
21 var aLi = oUl.getElementsByTagName("li");
22
23 oUl.onmouseover = function(ev){
24 var oEvent = ev || window.event;
25 var target = oEvent.target || oEvent.srcElement;
26 if( target.tagName.toLowerCase() == "li" ){
27 target.style.backgroundColor = "red";//防止移到ul上也觸發(fā)
28 }
29 };
30 oUl.onmouseout = function(ev){
31 var oEvent = ev || window.event;
32 var target = oEvent.target || oEvent.srcElement;
33
34 if( target.tagName.toLowerCase() == "li" ){
35 target.style.backgroundColor = "";//防止移到ul上也觸發(fā)
36 }
37 };
38
39
40 var oBtn = document.getElementById("btn1");
41 oBtn.onclick = function(){
42 var oLi = document.createElement("li");
43 oLi.innerHTML = "aaa";
44 oUl.appendChild(oLi);
45 };
46 </script>
47 </body>
48 </html>
?
轉(zhuǎn)載于:https://www.cnblogs.com/jiujiaoyangkang/p/5877646.html
總結(jié)
- 上一篇: jquery中动画效果的函数
- 下一篇: 257. Binary Tree Pat