JS插件封装——生成表格

来源:互联网 发布:软件脱壳工具 编辑:程序博客网 时间:2024/05/21 11:04

调用页面HTML代码如下:

<!DOCTYPE html><html lang="zh-cn"><head><meta charset="UTF-8"><title>Document</title></head><body><div>输入行数: <input type="text" name="" id="rows"><br>输入列数:<input type="text" name="" id="cols"><hr><input type="button" value="生成表格" onclick="build()"></div><div id="table"></div><script src="table.js"></script><script>function build(){var rows=document.getElementById("rows").value;var cols=document.getElementById("cols").value;var table=new Table(document.getElementById("table"));document.getElementById("table").innerHTML="";table.createTable({rows:rows,cols:cols});}</script></body></html>
插件js代码如下:

(function(){window.Table=function(node){this.nodeEle=node;this.width=node.clientWidth;//console.log("创建Table成功");}Table.prototype={createTable:function(json){if(!json){throw "Place check your rows and cols";}else{this.width=this.width/json.cols;this.cssStyle();console.log(this.width);//console.log("行数为:"+json.rows+"\n列数为:"+json.cols);/*生成行*/for(var i=0,rows=json.rows;i<rows;i++){var rowNode=document.createElement("div");rowNode.className = "row";if(i%2){rowNode.className += " double";}/*生成列*/for(var j=0,cols=json.cols;j<cols;j++){var colNode=document.createElement("div");colNode.className="col";rowNode.appendChild(colNode);}this.nodeEle.appendChild(rowNode);}}//console.log(this.nodeEle);},cssStyle:function(){var style=document.getElementsByTagName("style")[0];if(!style){style=document.createElement("style");}style.innerHTML += " #table .col{float:left;width:"+this.width+"px;box-sizing:border-box;border:1px solid #999;height:36px}" + " #table .row::after{content:'';display:block;clear:both;}" + " #table .double{background-color:skyblue}";document.head.appendChild(style);},};}());

页面效果如下:

知识点:

一、插件是功能的集合  例如jQuery和vue.js,面向的开发人员,而不是普通客户
插件都是写在函数作用域中的,并暴露出一个 实例(对象)or构造函数(产生对象的构造函数)
函数作用域,防止变量冲突
函数作用域中声明全局函数
(function(){
window.fn=function(){   

}
})();
//IIEF(立即执行函数) 通过作用域在全局作用域下暴露一个名字

插件封装原则:
1、暴露出来的实例必须只有一个
2、IIFE包裹   !执行包裹  函数作用域保护
3、实例方法不要写在函数中


备注:style.width    可改不可读

f.__proto__ ===fn.prototype;   //true   __proto__:关系的维持

原型链:关系
JS参考的为C和self语言

原创粉丝点击