×

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

作者:Terry2017.02.03来源:Web前端之家浏览:9528评论:0
关键词:JQueryJS
尽管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>

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/svg1486051200557.html

网友评论文明上网理性发言已有0人参与

发表评论: