这是一个自己写的创建div的方法,想要模块话,不知道这样写有没有优化的空间,比如,希望该方法只剩成一个实例对象,如何避免将暴露出来的modules的init被重写,现在里面的方法之间也没有很好的解耦
let modules = (function(w, $) {
let mod = {};
let rootDom = $("#wl-extend");
let className = rootDom.attr("class");
let getClassNameDom = function() {
let _c = className.split(" ");
if (_c[0].indexOf("wl-extend") > -1) {
let _dom = _c[0].split("-");
return _dom[2];
} else {
throw "未获取需要创建的dom元素";
}
};
mod.init = function(obj) {
let color = obj.color || "red";
let colorbor = obj.borderColor || "#ccc";
let width = obj.width || "200px";
let height = obj.height || "50px";
let domName = getClassNameDom();
createDom(domName, color, colorbor, width, height);
};
let createDom = function(domName, color, colorbor, width, height) {
rootDom.html(`<${domName} id='wl-create-dom'></${domName}>`);
let childrenDom = $("#wl-create-dom");
childrenDom.css({
color: color,
border: `1px solid ${colorbor}`,
width: width + "px",
height: height + "px"
});
$("#wl-extend").append(childrenDom);
};
return mod;
})(window, jQuery);
$(function() {
modules.init({
width: 500,
height: 200,
borderColor: "red"
});
});