前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >for 循环中实现多个点击事件 原

for 循环中实现多个点击事件 原

作者头像
tianyawhl
发布2019-04-04 16:38:54
发布2019-04-04 16:38:54
8720
举报
文章被收录于专栏:前端之攻略前端之攻略

<script type="text/javascript">   function buttonInit(){       for(var i=1;i<4;i++){           var b=document.getElementById("button"+i);           b.addEventListener("click",function(){ alert("Button"+i);},false);       }   }   window.onload=buttonInit;   </script>   </head>   <body>   <button id="button1">Button1</button>   <button id="button2">Button2</button>   <button id="button3">Button3</button>   </body>   </html> 全部弹出button4 当注册事件结束后,i的值是4,当点击按钮时,事件函数function(){alert("button"+i)}这个匿名函数中没有i, 所有到buttonInit函数中找,此时的i为4,所有弹出button4  (但是此时确实是点击不同的按钮,只是都显示i=4)修改如下: <script> function buttonInit(){       for(var i=1;i<4;i++){      (function (arg) {         var b=document.getElementById("button"+i);            b.onclick=function(){alert("Button"+arg);};     })(i);     }   }   window.onload=buttonInit;  </script>  js改成如上可以弹出button1 ,button2 , button3 另一个例子 for(var i=0;i<3;i++){ setTimeOut(function(){ console.log(i) },500) }; 执行结果:3,3,3 所以上述函数应该写成: for(var i=0;i<3;i++){ (function(i){ setTimeOut(function(){ console.log(i) },500); })(i); } 另一种修改方法:把var改成let即可 for(let i=0;i<3;i++){ setTimeOut(function(){ console.log(i) },500) }; 这种情况创建了太多的定时器,如果i值非常大,会非常消耗资源,大大降低执行性能,优化如下,始终只有一个定时器    let i = 0;     let time = setInterval(output, 1000)     function output() {         if (i < 10) {             console.log(i)             console.log(time)             i++         } else {             clearInterval(time)         }     } 如果自定义参数  let i = 0;     let time = setInterval(function() {output(8)}, 1000)     function output(num){           if (i < num) {             console.log(i)             i++         } else {             clearInterval(time)         }     }     </script>

(adsbygoogle = window.adsbygoogle || []).push({});

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016/08/25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档