js设置元素的onclick传参方法

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">  
  2. <HTML>  
  3.  <HEAD>  
  4.   <TITLE> New Document </TITLE>  
  5.   <META NAME="Generator" CONTENT="EditPlus">  
  6.   <META NAME="Author" CONTENT="">  
  7.   <META NAME="Keywords" CONTENT="">  
  8.   <META NAME="Description" CONTENT="">  
  9.   <script>  
  10.   var array=[1,2,3,4,5,6];  
  11.   function testvalue(val)  
  12. {  
  13.    alert(val);  
  14. }  
  15.    
  16.    
  17.   function add(){  
  18.    for(i=0,len=array.length;i<len;i++)                                                                   
  19.         {            
  20.           var newOption = document.createElement("li");  
  21.           newOption.innerHTML=i+1;  
  22.           newOption.onclick=function (val){ return function(){testvalue(val);}}(array[i])  
  23.              
  24. document.getElementById('div').appendChild(newOption);  
  25.    
  26.         }  
  27. }  
  28.    
  29.   </script>  
  30.  </HEAD>  
  31.    
  32.  <BODY>  
  33.   <input type='button' value='click me' onclick='add()' />  
  34. <div id='div'></div>  
  35.  </BODY>  
  36. </HTML>  
[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. <!DOCTYPE HTML>  
  2. <html>  
  3. <head>  
  4. <script type="text/javascript">  
  5.   
  6.   
  7. </script>  
  8.   
  9. </head>  
  10. <body>  
  11.   
  12. <div id="showDiv">  
  13.      this is showDiv  
  14. </div>  
  15. </body>  
  16. <script type="text/javascript">  
  17. var arr = new Array("a","b","c");  
  18. funcA();  
  19. function funcA(){  
  20.   var str = "";  
  21.   for(var m=0;m<arr.length;m++){  
  22.     str +=arr[m];  
  23.       
  24.     var a = document.createElement("A");  
  25.     var textStr = document.createTextNode("链接到"+m);  
  26.     a.appendChild(textStr);  
  27.     a.href="javascript:void(0)";  
  28.     a.onclick=function (val){ return function(){funcB(val);}}(m);  
  29.     var s = document.getElementById("showDiv");  
  30.       
  31.     s.appendChild(a);  
  32.       
  33.   }  
  34.   
  35. }  
  36. function funcB(m){  
  37.   alert("打开超链接"+m);  
  38. }  
  39. </script>  
  40. </html>  
原文地址:https://www.cnblogs.com/minghualiyan/p/4677646.html