在运行时在HTML中创建的新行的放置问题

我创建了一个表单,用户输入了详细信息,然后提交了该表单。假设添加的详细信息被保存为表格下方的一行。但是它们已被保存在表格标题上方。

以下是表格的HTML:

//Form to be filled
<form id="expense-form" action="" method="POST">
        <h2>Form to add expenses</h2>
        <div class="form-row">
            <div class="form-group col-md-6">
                <label for="description">Budget description:</label>
                <input type="text" id="description" class="form-control" placeholder="Add description" />
            </div>
            <div class="form-group col-md-6">
                <label for="category">Category:</label>
                <select id="category" name="category">
                    <option value="Rent">Rent</option>
                    <option value="EMI">EMI</option>
                    <option value="Groceries">Groceries</option>
                    <option value="Bills">Bills</option>
                    <option value="Others">Others</option>
                </select>
            </div>
            <div class="form-group col-md-6">
                <label for="expense-amount">Amount:</label>
                <input type="number" id="expense-amount" class="form-control" placeholder="Add amount" />
            </div>
            <div class="form-group col-md-6">
                <label for="date">Expense date:</label>
                <input type="date" id="date" class="date" placeholder="Add date of the expense" />
            </div>
        </div>
        <button type="submit" id="add-btn" class="btn btn-primary">Submit</button>
    </form>


        <!--The list of expenses-->
        <table id= "expense-table" class="table table-striped mt-5">
            <thead id="expense-table-head">
              <tr>
                <th>Expense description</th>
                <th>Category</th>
                <th>Amount</th>
                <th>Expense Date</th>
                <th></th>
              </tr>
            </thead>
            <tbody id="expense-list-display"></tbody>
          </table>

javascript函数是:

function addExpensetoList() {
var expenseDesc = document.getElementById("description").value;
var expenseCategory = document.getElementById("category").value;
var expenseAmount = document.getElementById("expense-amount").value;
var expenseDate = document.getElementById("date").value;

var table = document.getElementById("expense-table");
var row = table.insertRow(0);

var descCell = row.insertCell(0);
var categoryCell = row.insertCell(1);
var amountCell = row.insertCell(2);
var dateCell = row.insertCell(3);

descCell.innerHTML = expenseDesc;
categoryCell.innerHTML = expenseCategory;
amountCell.innerHTML = expenseAmount;
dateCell.innerHTML = expenseDate;}

When I enter the data, and submit form, that data is saved as: enter image description here

有人可以告诉我我在做什么错吗?

评论
  • 间接性抑郁
    间接性抑郁 回复

    var row = table.insertRow(0);是问题。如果仅使用table.insertRow(),它将追加为最后一行