当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 远离JS灾难css灾难之js私有函数和css选择器作为容器

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

2018年10月09日  | 移动技术网IT编程  | 我要评论

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

代码如下:


<html xmlns="https://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.makep = 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("https://images.cnblogs.com/logo_small.gif", "#test");
mytest.makep(10);
var mytest2 = new publicsetdiv("https://images.cnblogs.com/logo_small.gif", "#test2");
mytest2.makep(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">
第一次使用
<p id="test" style=" display:none;">
</p>
<p id="test2" style=" display:none;">
</p>
</form>
</body>
</html>

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网