在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
关于 let 避免闭包带来的问题
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <!--code here--> <title>demo</title> <style> * { padding: 0; margin: 0; } .head, li div { display: inline-block; width: 70px; text-align: center; } li .id, li .sex, .id, .sex { width: 15px; } li .name, .name { width: 40px; } li .tel, .tel { width: 90px; } li .del, .del { width: 15px; } ul { list-style: none; } .user-delete { cursor: pointer; } </style> </head> <body> <div id="J_container"> <div class="record-head"> <div class="head id">序号</div> <div class="head name">姓名</div> <div class="head sex">性别</div> <div class="head tel">电话号码</div> <div class="head province">省份</div> <div class="head">操作</div> </div> <ul id="J_List"> <li> <div class="id">1</div> <div class="name">张三</div> <div class="sex">男</div> <div class="tel">13788888888</div> <div class="province">浙江</div> <div class="user-delete">删除</div> </li> <li> <div class="id">2</div> <div class="name">李四</div> <div class="sex">女</div> <div class="tel">13788887777</div> <div class="province">四川</div> <div class="user-delete">删除</div> </li> <li> <div class="id">3</div> <div class="name">王二</div> <div class="sex">男</div> <div class="tel">13788889999</div> <div class="province">广东</div> <div class="user-delete">删除</div> </li> </ul> </div> <script> // 此处也可换成ES6的写法 function Contact() { this.init(); } // your code here </script> </body> </html> code1
code2 ( 别人的代码 ) Contact.prototype.init = function () { console.log("Test"); var div = document.getElementsByClassName("user-delete"); var ul = document.querySelector("#J_List"); var list = ul.querySelectorAll("li"); for (var i = 0; i < div.length; i++) { (function (i) { div[i].onclick = function () { list[i].remove(); console.log(i); } })(i); } } new Contact(); 其中 (function (i) { div[i].onclick = function () { list[i].remove(); console.log(i); } })(i); 这段立即执行函数没看懂意义 我的代码 Contact.prototype.init = function () { let div = document.getElementsByClassName("user-delete"); let ul = document.querySelector("#J_List"); let list = ul.querySelectorAll("li"); for (let i in div) { div[i].onclick = function () { list[i].remove(); console.log(i); } } } new Contact(); 后来想起来是为了避免闭包带来的问题,这一段廖雪峰老师讲过,但是一时没有想起来,详见 廖雪峰闭包
到此这篇关于JavaScript中let避免闭包造成问题的文章就介绍到这了,更多相关JavaScript中let闭包问题内容请搜索极客世界以前的文章或继续浏览下面的相关文章希望大家以后多多支持极客世界! |
请发表评论