form.elements 获取所有表单元素
form 表单
js 代码
let l = console.log; function qs(s) { return document.querySelector(s) } let toArray = Array.from; let f = qs('.form') let body = {} scanDOM(f); function scanDOM(box) { let eles = toArray(box.children) for (let ele of eles) { if (ele.children.length && ele.nodeName !== 'SELECT' && ele.nodeName !== 'FIELDSET') { // select元素没有必要递归,表单包也暂时不用遍历 scanDOM(ele) } else { let nodeName = ele.nodeName.toLowerCase(); let formElementp = (v) => v === 'input' || v === 'select' || v === 'textarea' || v === 'fieldset'; if (formElementp(nodeName)) { // 确认元素是表单元素 if (ele.disabled === true) continue; // 如果元素为禁用则跳过 let k, v; k = ele.name; if (!k) continue; // 没有name的表单元素跳过 if (ele.type === 'radio') { // 单选按钮时,需要判断是否为选中状态 if (!ele.checked) continue; v = ele.value; } else if (ele.type === 'checkbox') { if (!ele.checked) continue; v = ele.value; } else { if (nodeName === 'select' && ele.multiple) { let vs = []; // 收集所有多选状态下的 selected的value, let options = toArray(ele.children); for (let o of options) { vs.push(o.value) } v = vs; } else if (nodeName === 'fieldset') { scanDOM(ele) } else { v = ele.value; } } if(v === undefined) continue; let alive = k in body; if (alive) { // 已经存在相应的name let ov = body[k] if (Object.prototype.toString.call(body[k]) === '[object Array]') { body[k] = ov.concat(v) } else { body[k] = [ov, v] } } else { body[k] = v; } } } } } l(body)