费用追踪器开发求助:JavaScript实现按钮与表格数据联动显示
问题描述
我已经完成了费用追踪器(Expense Tracker)的大部分HTML和CSS开发,但在JavaScript部分遇到了困难。我需要把添加按钮和表格关联起来,实现点击按钮后将表单里的数据显示到表格中,但不清楚具体的实现思路。
我只写了一个函数,用了getElementById()方法,代码如下:
现有JavaScript代码
function addExpense() { var expenses = document.getElementById("data"); }
现有HTML代码
<body> <h1>Expense Tracker</h1> <h2>ADD NEW ITEM:</h2> <form id="data"> <label>Name:</label> <input type="text" id="name" name="submit" placeholder="Where was the expense made?" /> <p></p> <label>Date:</label> <input type="date" id="date" name="dates" placeholder="mm/dd/yyyy" /> <label>Amount:</label> <input type="number" id="Amount" name="Amount" /> <p></p> <button type="button" onclick="addExpense()">Add expense</button> </form> <table> <tbody> <tr> <th>name</th> <th>date</th> <th>Amount</th> </tr> <tr id="row"> <th></th> <th></th> <th></th> </tr> </tbody> </table> </body>
解决方案
要实现点击按钮把表单数据加到表格里,核心要做这几步:拿表单里的输入值、新建表格行和单元格、把值填进去再加到表格里,最后清空表单方便下次输入。具体实现代码如下:
修改后的JavaScript代码
function addExpense() { // 1. 把表单里的输入值取出来 const expenseName = document.getElementById("name").value.trim(); const expenseDate = document.getElementById("date").value; const expenseAmount = document.getElementById("Amount").value.trim(); // 先检查下有没有空字段,别加空数据进去 if (!expenseName || !expenseDate || !expenseAmount) { alert("所有字段都得填哦!"); return; } // 2. 找到表格的tbody,新行要加到这里面 const tableBody = document.querySelector("table tbody"); // 3. 新建一行<tr>和三个单元格<td> const newRow = document.createElement("tr"); const nameCell = document.createElement("td"); const dateCell = document.createElement("td"); const amountCell = document.createElement("td"); // 4. 把取到的值放进单元格里 nameCell.textContent = expenseName; dateCell.textContent = expenseDate; amountCell.textContent = `$${expenseAmount}`; // 加个美元符号看着更像费用记录 // 5. 把单元格拼到新行,再把新行加到表格里 newRow.appendChild(nameCell); newRow.appendChild(dateCell); newRow.appendChild(amountCell); tableBody.appendChild(newRow); // 6. 清空表单,方便下次输入 document.getElementById("data").reset(); }
HTML小调整
你原来表格里有个空的<tr id="row">,要是不需要这个默认空行,直接删掉就行,表格初始只留表头:
<table> <tbody> <tr> <th>name</th> <th>date</th> <th>Amount</th> </tr> <!-- 新行会通过JS动态添加,这里不用留空行 --> </tbody> </table>
思路拆解
- 取输入值:用
getElementById()拿到每个输入框的内容,trim()去掉首尾空格,防止用户只打空格提交。 - 检查输入:简单判断下有没有空字段,避免无效数据进表格。
- 建DOM元素:用
document.createElement()生成新的行和单元格,这是网页动态加内容的常规操作。 - 拼到表格里:把值塞给单元格,再把单元格挂到新行,最后把新行加到表格的tbody里。
- 重置表单:调用表单的
reset()方法清空所有输入框,用户不用手动删,体验更好。
内容的提问来源于stack exchange,提问作者Nadir Esmail
相关产品推荐
相关产品推荐

