介绍:
方便动态插入html代码,根据json生成html代码,代码如下。
代码:
html部分
js部分var jsonToHtml = {}
jsonToHtml.css = function (css) {
var style = document.createElement('style');
style.type = 'text/css';
style.rel = 'stylesheet';
try {
style.appendChild(document.createTextNode(css));
} catch (ex) {
style.styleSheet.cssText = css;
}
document.querySelector('head').appendChild(style);
}
jsonToHtml.html = function (el, arr) {
var keys = ["childs", "element"];
arr.forEach(item => {
var element = document.createElement(item.element);
for (let key in item) {
if (keys.indexOf(key) == -1) {
element[key] = item[key];
}
}
if (item.childs) {
this.html(element, item.childs)
}
el.appendChild(element);
});
}
实例var data = [{
element: "h1",
className: "title",
innerText: "创建div"
},
{
element: "div",
id: "wrap",
className: "wrap",
childs: [{
element: "ul",
childs: [{
element: "li",
className: "wrap-li",
innerText: "文本",
childs: [{
element: "input",
type: "checkbox",
checked: true,
disabled: true
}]
}, {
element: "li",
className: "wrap-li",
childs: [{
element: "input",
type: "text",
placeholder: "haha"
}]
}]
}]
}
]
var el = document.querySelector("#app");
jsonToHtml.html(el, data);
jsonToHtml.css('body{background:#ccc}');