根据数据生成表单
<head>
<meta charset="UTF-8">
<title>生成表单</title>
<script>
window.onload = function() {
//创建form 1)创建label
var form = document.createElement("form");
var arr = [{
label: "用户名",
name: "username",
type: "text"
}, {
label: "密码",
name: "password",
type: "password"
}, {
label: "性别",
name: "gender",
type: "select",
value: ['男', '女']
}, {
label: "爱好",
name: "hobby",
type: "checkbox",
value: ['篮球', '足球', '羽毛球', '兵乓球', '爬山', '购物', '旅游', '看美女']
}, {
label: '是否已婚',
name: 'married',
type: 'radio',
value: ['已婚', '未婚']
}];
for(var i = 0; i < arr.length; i++) {
var label = document.createElement("label");
var p = document.createElement("p")
label.innerHTML = arr[i].label + ":";
if(arr[i].type == "text" || arr[i].type == "password") {
var input = document.createElement("input");
input.setAttribute("name", arr[i].name);
input.setAttribute("type", arr[i].type);
label.appendChild(input);
}
else if(arr[i].type == "select") {
var select = document.createElement("select");
var option = document.createElement("option");
var optio = document.createElement("option");
//
option.innerHTML = arr[i].value[0];
optio.innerHTML = arr[i].value[1];
//需要给下拉框一个value值
option.value=arr[i].value[0];
optio.value=arr[i].value[1];
select.appendChild(option);
select.appendChild(optio);
label.appendChild(select);
}
else if(arr[i].type == "checkbox" || arr[i].type == "radio") {
var check = arr[i].value;
for(var j = 0; j < check.length; j++) {
var input = document.createElement("input");
var span = document.createElement("span");
span.innerHTML = arr[i].value[j];
input.setAttribute("name", arr[i].name);
input.setAttribute("type", arr[i].type);
input.setAttribute("value", arr[i].value);
label.appendChild(span);
label.appendChild(input);
}
}
p.appendChild(label);
form.appendChild(p);
document.body.appendChild(form);
}
}
</script>
</head>
<body>
</body>