远离JS灾难css灾难之 js私有函数和css选择器作为容器

  当一个项目庞大到一定阶段,例如UI展示层采用了模块化模板化之后,就会出现js灾难,css灾难,经常出现以前从来不放在一起的两个js或css莫名奇妙的被放到了一个页面,基本的原因是模块重用造成的

    尽管js可以想面向对象那样去构造对象,隐藏私有方法,但需求变化的往往比你写程序还要快时,就连设计js对象的时间也没有了,所以我比较倾向于用js私有函数和js方法;jquery私有函数和jquery对外暴露方法的形式也可以实现,而页面生成的html结构则完全在js中生成,包括哪些id和class, 这样可以最大限度的确保统一和重用的方便性,但也有个缺点,就是在重用时,如果需要样式发生变化(结构是死的不能变化),就需要用div将原来的结构包起来,相关的样式也需要用对应的id包裹一遍,如果是新增的事件等就只能采用绑定的方式,暂时还没有好的方法

例如,我面要实现 在一个div中包含几张图片

这样做也有个缺点 就只 css 必须得复制一次 在做修改 但对结构和样式以及js可以重用

 

 

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">

        var publicSetDiv = function (url, id) {
            //作为对外公开的,可以传参就行
            this.makediv = function (j) {
                var imglist = makeimglist(url, j);
                $(id).html(imglist);
                $(id).show();
            }

            //私有的
            function makeimglist(url, j) {
                var i = 0;
                //var j = 10;
                var html = "";

                for (i; i < j; i++) {
                    html += "<img src='" + url + "' class='item' />";
                }
                return html;
            }


        }



        $(document).ready(function () {
            // Handler for .ready() called.
            var mytest = new publicSetDiv("http://images.cnblogs.com/logo_small.gif", "#test");
            mytest.makediv(10);

            var mytest2 = new publicSetDiv("http://images.cnblogs.com/logo_small.gif", "#test2");
            mytest2.makediv(10);
        });
    


    </script>
<%--    原始默认 的样式--%>
    <style type="text/css">
        .item{ width:200px; height:100px; }
        

        #test2 .item{ width:200px; height:100px; }
    </style>
<%--     第二次使用该样式并稍作修改  --%>
        <style type="text/css">
        #test2 .item{ width:200px; height:200px;  background-color:Black; }
    </style>

</head>
<body>
    <form id="form1" runat="server">
    第一次使用
    <div id="test" style=" display:none;">
    </div>

   <div id="test2" style=" display:none;">
    </div>


    </form>
</body>
</html>
posted @ 2011-12-10 16:31  互联网Fans  阅读(676)  评论(0编辑  收藏  举报