• 用闭包减少代码


    做一个radiolist控制textbox显示隐藏的功能,最初的代码:

    rblSecurityCameras = document.getElementsByName("<%=rblSecurityCameras.UniqueID %>");
            txtSecurityCameras = document.getElementById("<%=txtSecurityCameras.ClientID %>");
    
    
            for (i in rblSecurityCameras) {
                rblSecurityCameras[i].onclick = function(){
                    if (this.value == "2" && this.checked) {
                        txtSecurityCameras.style.display = 'none';
                    }
                    else if (this.value == "1" && this.checked) {
                        txtSecurityCameras.style.display = '';
                    }
    };
                 if (rblSecurityCameras[i].value == "2" && rblSecurityCameras[i].checked) {
                        txtSecurityCameras.style.display = 'none';
                    }
                    else if (rblSecurityCameras[i].value == "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 == "2" && obj.checked) {
     7                     txt.style.display = 'none';
     8                 }
     9                 else if (obj.value == "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         }
  • 相关阅读:
    17、静态链表
    16、约瑟夫问题
    15、循环链表
    9、插入排序
    14、企业链表
    13、单向链表
    12、顺序表的顺序存储结构
    11、归并排序
    10、快速排序
    原型模式
  • 原文地址:https://www.cnblogs.com/405464904/p/3740484.html
Copyright © 2020-2023  润新知