javascript - 执行代码后出现错误 TypeError: display is nullscript.js:22:22
问题描述
HTML 这是一个 HTML 页面,当用户单击“添加”按钮时,我在表格中一个接一个地添加行,并给出如下错误。
<div id="adder">
<table id="adderhd">
<tr>
<th>PARTICULARS</th>
<th>Amount</th>
</tr>
<tr>
<th><input type="text" id="particulars" value=""></th>
<th><input type="number" id="amount" value=""><button id="add">Add</button></th>
</tr>
</table>
</div>
<div id="tables">
<div>
<table class="table-1">
<tr>
<th>
PARTICULARS
</th>
<th>
AMOUNT
</th>
</tr>
</table>
</div>
</div>
JavaScript 这是我为它编写的 JavaScript 代码,但执行此代码后,我在控制台上出现错误。
请帮助我,我是 JavaScript 的初学者。
function rowAdder() {
var particulars = document.getElementById("particulars").value;
var amount = document.getElementById("amount").value;
if (!particulars || !amount) {
alert("Please enter the values inside all the field.");
return;
}
var display = document.getElementById("table-1");
var newRow = display.insertRow(row); //not working (insert(row));
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
cel1.innerHTML = particulars;
cel2.innerHTML = amount;
row++;
}
解决方案
您需要在按钮上添加一个事件 onclick 以调用 rowAdder 函数。变量“显示”通过 id 获取元素,因此将 id="table-1" 分配给您的 html 元素。它工作正常。
function rowAdder() {
var particulars = document.getElementById("particulars").value;
var amount = document.getElementById("amount").value;
if (!particulars || !amount) {
alert("Please enter the values inside all the field.");
return;
}
var display = document.getElementById("table-1");
var newRow = display.insertRow();
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
cel1.innerHTML = particulars;
cel2.innerHTML = amount;
}
<div id="adder">
<table id="adderhd">
<tr>
<th>PARTICULARS</th>
<th>Amount</th>
</tr>
<tr>
<th><input type="text" id="particulars" value=""></th>
<th><input type="number" id="amount" value="">
<button onclick="rowAdder()"id="add">Add</button></th>
</tr>
</table>
</div>
<div id="tables">
<div>
<table id="table-1">
<tr>
<th>
PARTICULARS
</th>
<th>
AMOUNT
</th>
</tr>
</table>
</div>
</div>
推荐阅读
- python-3.x - 如何部分提取列表中的项目?
- java - 使用 Apache POI 更新股票图表
- python - 如何显示鹡鸰页面的孩子
- database - 存储 MongoDB 帐户的推荐数据库是什么?
- c# - Unity - Vuforia - Raycast Hits 在 Unity 编辑器上运行良好,但在 Android 设备构建上存在错误
- python - extractText() 函数不返回文本
- javascript - 我的网站在较小的设备上没有响应
- xquery - 使用 MarkLogic Java API 与 QConsole 的通配符搜索无法按预期工作
- tensorflow - 为什么当我使用 numpy 数学时 GradientTape 返回 None
- django - GET Body 没有与 APIClient Django DRF 一起发送