如何将存储表单字段的JavaScript变量拆分到HTML表格同一行单元格?
解决方案
我来帮你搞定这个问题!你当前的代码只是把所有表单字段的值拼接成一串文本直接插入表格行,自然没法拆分成独立的单元格。咱们只需要调整JavaScript的逻辑,让每个字段值对应一个<td>元素,同时完善表格的表头结构即可。
核心修改点
- JavaScript部分:循环表单元素时,为每个字段值包裹
<td>标签,这样插入到表格行后会自动成为独立单元格 - HTML表头:补充完整5个字段的表头,让表格结构更合理
修改后的完整代码
JavaScript
function getInfo() { var info = document.getElementById("form1"); var tableCells = ""; var i; // 循环表单元素,为每个值创建一个表格单元格 for (i = 0; i < info.length; i++) { // 过滤掉可能存在的非文本输入元素 if (info.elements[i].type === "text") { tableCells += `<td>${info.elements[i].value}</td>`; } } // 将生成的单元格插入到表格行中 document.getElementById("data").innerHTML = tableCells; // 控制台输出验证 console.log(tableCells); }
CSS
div.ui-input-text { width: 200px !important;} button { width: 200px !important; }
HTML
<!-- JQuery styling and CDN files --> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" /> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script> <!-- Form HTML --> <form id="form1"> First name: <input type="text" name="fname" id="fname1" required><br> Last name: <input type="text" name="lname" id="lname1" required><br> Address: <input type="text" name="address" id="address1" required><br> City: <input type="text" name="city" id="city1" required><br> State: <input type="text" name="state" id="state1" required><br> </form> <p>Click the button below to display your entry.</p> <!-- Javascript button to capture and display the input --> <button onclick="getInfo()">Try it</button> <table style="width:100%"> <tr> <th>First Name</th> <th>Last Name</th> <th>Address</th> <th>City</th> <th>State</th> </tr> <tr id ="data"> </tr> </table>
逻辑说明
- 我们把原来的
text变量改成tableCells,每次循环都会为当前表单字段的值生成一个<td>元素,把值包裹在里面 - 添加了
type === "text"的判断,避免意外处理表单中可能存在的其他类型元素(比如隐藏域、提交按钮等) - 完善了表格的表头,让每个数据单元格都有对应的表头,符合表格的语义化结构
- 最后把生成的所有
<td>元素插入到表格行<tr id="data">中,浏览器会自动渲染成同一行的5个独立单元格
内容的提问来源于stack exchange,提问作者CodingTime
相关产品推荐
相关产品推荐

