我花了很多时间做类似这样的事情,在我的努力中,我建立了一个非常高效的框架,采用面向对象的方法,稍微复杂一些,但它可以快速开发,并具有像API一样的接口。
- 以代码中所示的简单语法声明JSON对象
- 声明一个特定于对象的create方法(Form.prototype.create),并指定如何构建对象。
- 然后只需调用Build()函数并将JSON对象作为参数传递。 例如--- Build(signin)
//CODE
<!DOCTYPE html>
<html>
<head>
<script>
var signin = [
{"container":{"element": "aside", "attributes": {"id":"overlay","class":"overlay1","onclick":"Destroy(event);"}}},
{"form":{"element": "form", "attributes": {"id":"form"}}},
{"msg":{"element": "mark", "attributes": {"id":"form-msg"}}},
{"ipt1":{"element": "input", "attributes": {"type":"email","placeholder":"email","name":"email"}}},
{"ipt2":{"element": "input", "attributes": {"type":"password","placeholder":"password","name":"password"}}},
{"ipt3":{"element": "input", "attributes": {"type":"button","value":"Sign In","class":"form-btn btn-blue", "data-url":"/core/signin.php","onclick":"Submit(this);"}}},
{"ipt4":{"element": "input", "attributes": {"type":"button","value":"Account Recovery","class":"form-btn btn-black","data-form":"recover","onclick":"Build(recover)"}}}
];
function Build(obj){
var form = Form.new(obj);
form.assemble();
form.create();
}
function Form(){
for(var i=0; i < arguments.length; i++){
var key = Object.keys(arguments[i]);
this[key] = arguments[i][key];
}
}
Form.prototype.create = function(){
var inpts = Object.keys(this).splice(3);
var container = document.body.appendChild(this.container);
var form = container.appendChild(this.form);
container.appendChild(this.msg);
for(i=0; i < inpts.length; i++){
form.appendChild(this[inpts[i]]);
}
}
Function.prototype.new = function (args) {
var Fake = Object.create(this.prototype);
this.apply(Fake, args);
return Fake;
};
Object.prototype.assemble = function(){
for(key in this){
if(this.hasOwnProperty(key)){
var element = document.createElement(this[key].element);
var attributes = this[key].attributes;
for(prop in attributes){
if(attributes.hasOwnProperty(prop)){
element.setAttribute(prop, attributes[prop]);
this[key] = element;
}
}
}
}
}
</script>
</head>
<body></body>
</html>