1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title> 6 javascript闭包实例 7 </title> 8 <style> 9 #pmenu { margin-left: auto;margin-right: auto;} 10 ul.adminLeftNav{width:140px;border:1px solid #A8C8EE;border-bottom:0px;list-style:none;margin:0;padding:0;text-align:left;} 11 ul.adminLeftNav li{ line-height:34px;font-size:12px;color:#0B6BB3;font-weight:bold;border-bottom:1px solid #A8C8EE; 12 background:url(/eaf/images/cmail_7.gif) no-repeat 20px 12px;text-indent:40px;cursor:pointer;background-color:#FFFFFF;} 13 ul.adminLeftNav li:hover{background-color:#C4E7DE;} 14 ul.adminLeftNav li.hover{background-color:#C4E7DE;} 15 ul.adminLeftNav li div{display:none;border-top:1px solid #A8C8EE;padding:5px 0;background:#fff;} 16 ul.adminLeftNav li div a{display:block;line-height:20px;text-indent:30px;font-weight:normal;color:#000;text-decoration:none;} 17 ul.adminLeftNav li div a:hover{text-decoration:underline;} 18 </style> 19 <script type="text/javascript"> 20 window.onload = function() { 21 var obj1 = document.getElementById("pmenu").getElementsByTagName("li"); 22 for(var i=0;i<obj1.length;i++) 23 { 24 //闭包实现给对象添加事件 25 (function(){ 26 var temp = obj1[i]; 27 temp.onmouseover = function(){temp.className='hover';} 28 } 29 )(); 30 (function(){ 31 var temp = obj1[i]; 32 temp.onmouseout = function(){temp.className='';} 33 } 34 )(); 35 (function(){ 36 var idNum = i; 37 obj1[idNum].onclick = function(){showChildMenu('p1'+idNum,'#',idNum+1);} 38 } 39 )(); 40 } 41 // idNum作为内部函数变量被传递出来 42 function showChildMenu(id,url,num){ 43 alert("您点击的是第"+ num +"个菜单"); 44 var obj = document.getElementById("pmenu").getElementsByTagName("div"); 45 for(var i=0;i<obj.length;i++) 46 { 47 obj[i].style.display='none'; 48 } 49 if(id!='') { 50 document.getElementById(id).style.display='block'; 51 } 52 } 53 } 54 </script> 55 </head> 56 57 <body> 58 <ul id="pmenu" class="adminLeftNav"> 59 <li >菜单1 60 <div id="p10"> 61 <a href="#">菜单</a> 62 <a href="#">菜单</a> 63 <a href="#">菜单</a> 64 </div> 65 </li> 66 <li >菜单2 67 <div id="p11"> 68 <a href="#">菜单</a> 69 <a href="#">菜单</a> 70 <a href="#">菜单</a> 71 <a href="#">菜单</a> 72 <a href="#">菜单</a> 73 </div> 74 </li> 75 <li >菜单3 76 <div id="p12"> 77 <a href="#">菜单</a> 78 <a href="#">菜单</a> 79 <a href="#">菜单</a> 80 <a href="#">菜单</a> 81 <a href="#">菜单</a> 82 </div> 83 </li> 84 <li >菜单4 85 <div id="p13"> 86 <a href="#">菜单</a> 87 <a href="#">菜单</a> 88 <a href="#">菜单</a> 89 <a href="#">菜单</a> 90 <a href="#">菜单</a> 91 </div> 92 </li> 93 <li >菜单5 94 <div id="p14"> 95 <a href="#">菜单</a> 96 <a href="#">菜单</a> 97 <a href="#">菜单</a> 98 <a href="#">菜单</a> 99 </div> 100 </li> 101 <li >菜单6 102 <div id="p15"> 103 <a href="#">菜单</a> 104 </div> 105 </li> 106 </ul> 107 </body> 108 </html>