首页 > 解决方案 > 执行代码后出现错误 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++;

}

标签: javascripthtmljqueryforms

解决方案


您需要在按钮上添加一个事件 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> 


推荐阅读