如何将表单每次提交的输入值以对象形式存入数组?
解决方案:将提交数据封装为对象存入数组
嘿,作为前端新手能写出这样的交互已经很棒啦!要实现每次提交把输入的三个值封装成对象并存储到数组里,只需要对你的JavaScript代码做几处简单修改,咱们来看具体步骤:
1. 声明全局存储数组
首先,在你的post函数外面声明一个数组,用来保存所有提交记录——这样每次调用函数时数组不会被重置,能持续存储数据:
// 全局声明存储数组 let submissions = []; function post(event) { event.preventDefault(); // ... 原函数内容 }
2. 封装提交数据为对象并推入数组
在获取到三个输入框的值之后,把它们打包成一个结构清晰的对象,然后推到数组里:
function post(event) { event.preventDefault(); const data = document.getElementById("data"); // 建议把var改成const,更符合现代JS规范 const nameValue = document.getElementById("name").value; const pname = document.getElementById("pname").value; const ptype = document.getElementById("ptype").value; // 封装为对象 const newSubmission = { personName: nameValue, productType: ptype, productName: pname }; // 推入数组 submissions.push(newSubmission); // 可选:控制台打印数组,方便查看存储结果 console.log("当前所有提交记录:", submissions); // ... 原函数里创建DOM元素和重置表单的代码 }
修改后的完整JavaScript代码
let submissions = []; function post(event) { event.preventDefault(); const data = document.getElementById("data"); const nameValue = document.getElementById("name").value; const pname = document.getElementById("pname").value; const ptype = document.getElementById("ptype").value; // 封装对象并存入数组 const newSubmission = { personName: nameValue, productType: ptype, productName: pname }; submissions.push(newSubmission); console.log("所有提交记录:", submissions); // 原有的DOM渲染逻辑 const name = document.createElement("p"); name.appendChild(document.createTextNode(nameValue)); name.setAttribute("class", "perName"); data.appendChild(name); const product_type = document.createElement("p"); product_type.appendChild(document.createTextNode(ptype)); product_type.setAttribute("class", "prodType"); data.appendChild(product_type); const product_name = document.createElement("p"); product_name.appendChild(document.createTextNode(pname)); product_name.setAttribute("class", "prodName"); data.appendChild(product_name); document.getElementById("myForm").reset(); }
小提示
- 用
const声明不会重新赋值的变量(比如nameValue)是更规范的写法,比var更安全。 - 对象的键名(比如
personName、productType)可以根据你的需求自定义,只要语义清晰就行。 - 打开浏览器的开发者工具(F12),切换到Console标签,每次提交后就能看到数组里的存储内容啦。
内容的提问来源于stack exchange,提问作者Gunasethu
相关产品推荐
相关产品推荐

