首页 > 代码库 > 用闭包减少代码
用闭包减少代码
做一个radiolist控制textbox显示隐藏的功能,最初的代码:
rblSecurityCameras = document.getElementsByName("<%=rblSecurityCameras.UniqueID %>"); txtSecurityCameras = document.getElementById("<%=txtSecurityCameras.ClientID %>"); for (i in rblSecurityCameras) { rblSecurityCameras[i].onclick = function(){ if (this.value =http://www.mamicode.com/="2" && this.checked) { txtSecurityCameras.style.display = ‘none‘; } else if (this.value =http://www.mamicode.com/="1" && this.checked) { txtSecurityCameras.style.display = ‘‘; } }; if (rblSecurityCameras[i].value =http://www.mamicode.com/="2" && rblSecurityCameras[i].checked) { txtSecurityCameras.style.display = ‘none‘; } else if (rblSecurityCameras[i].value =http://www.mamicode.com/="1" && rblSecurityCameras[i].checked) { txtSecurityCameras.style.display = ‘‘; } }
点击事件和load的过程的代码是相同的,有代码洁癖的我就不干了。
使用闭包
1 rblSecurityCameras = document.getElementsByName("<%=rblSecurityCameras.UniqueID %>"); 2 txtSecurityCameras = document.getElementById("<%=txtSecurityCameras.ClientID %>"); 3 4 var mm = function(obj, txt) { 5 return (function() { 6 if (obj.value =http://www.mamicode.com/="2" && obj.checked) { 7 txt.style.display = ‘none‘; 8 } 9 else if (obj.value =http://www.mamicode.com/="1" && obj.checked) { 10 txt.style.display = ‘‘; 11 } 12 }); 13 }; 14 15 for (i in rblSecurityCameras) { 16 rblSecurityCameras[i].onclick = mm(rblSecurityCameras[i], txtSecurityCameras); 17 mm(rblSecurityCameras[i], txtSecurityCameras)(); 18 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。