生成器函数生成表单字段是非常合适的用法,避免你要用纯javascript做后台时频繁的制作表单,而不能重复利用
//这里是javascript部分,formfiled.js
//生成器函数对字段的处理,让各字段name\className\label\value\placeholder赋值到input的属性上
function * formFieldGenerator(fields)
{
for(const field of fields)
{
switch(field.type)
{
case 'text':
if(field.value.trim()==='' || field.value.toString()==='undefined')
{
yield `${field.className}">${field.label}${field.name}" value="" placeholder="${field.placeholder}" autocomplete="off">`;
}else
{
yield `${field.className}">${field.label}${field.name}" value="${field.value}" placeholder="${field.placeholder}" autocomplete="off">`
}
break;
case 'email':
yield `${field.className}">${field.label}${field.name}" value="${field.value || ''}" placeholder="${field.placeholder}" autocomplete="off">`;
break;
case 'password':
yield `${field.className}">${field.label}${field.name}" value="${field.value||''}" autocomplete="off">`;
break;
case 'checkbox':
yield `" value="${field.value}">${field.label}`;
break;
case 'submit':
yield `${field.className}">${field.name}" value="${field.value}">`;
break;
case 'button':
yield `${field.className}">${field.name}" value="${field.value}">`;
break;
default:
yield ``;
}
}
}
//字段配置表,你需要生成那些字段,按类型进行编写
const formFields=[
{type:'text',name:'username',placeholder:'请输入用户名',value:'',label:'用 户 ',className:'regInput'},
{type:'password',name:'pwd',label:'密 码 ',className:'regInput'},
{type:'password',name:'pwd2',label:'重 复 ',className:'regInput'},
{type:'email',name:'yourEmail',placeholder:'输入电子邮件',label:'邮 件 ',className:'regInput'},
{type:'checkbox',name:'language',label:'javascript',value:'javascript'},
{type:'checkbox',name:'language',label:'php',value:'php'},
{type:'checkbox',name:'language',label:'java',value:'java'},
{type:'checkbox',name:'language',label:'nodejs',value:'nodejs'},
{type:'submit',name:'regsubmit',value:'提交',className:'btn1'},
];
//获取html上的容器,将创建的表单添加进去
const formHtml=document.createElement('form1');
//设置表单的属性
formHtml.setAttribute('action','submit_form.php');
formHtml.setAttribute('method','post');
formHtml.setAttribute('name','regform1');
//利用formFieldGenerator(formFields)生成器函数安字段配置表生成表单内容
formHtml.innerHTML=Array.from(formFieldGenerator(formFields)).join('');
//加入容器内
document.getElementById('container').appendChild(formHtml);
//前端生成表单index.html
DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
<title>用生成器生成表单title>
<style type="text/css">
#container
{
width: 1050px;
margin: 5px auto;
border: 1px solid red;
text-align: center;
font-size: 16px;
padding-top:10px;
}
.regInput
{
margin-bottom: 15px;
}
.regInput label
{
font-family: Arial, Helvetica, sans-serif;
}
.regInput input
{
text-indent: 5px;
}
.btn1
{
margin-top: 15px;
}
style>
head>
<body>
<div id="container">
div>
<script src="formfiled.js">script>
body>
html>