首页 > 代码库 > 用闭包减少代码

用闭包减少代码

 

做一个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         }