【问题标题】:"Undefined is not an object" When trying to reference a cell in HTML“未定义不是对象”尝试在 HTML 中引用单元格时
【发布时间】:2021-06-13 08:40:40
【问题描述】:

我正在尝试使用网站上用户的数据制作一个表格。我添加了删除行的选项,但出现错误

“未定义不是对象(正在评估'table.rows[i].cells[3]')”

如果我使用固定表格,我的代码可以工作,但是使用使表格可编辑的脚本不起作用,这是我的代码:

<html>
    <head>

        <title>Remove HTML Table Selected Row</title>
        <meta charset="windows-1252">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <style>
            td:last-child{background-color: #F00;color:#FFF;cursor: pointer;
                          font-weight: bold;text-decoration: underline}

        </style>

    </head>
    <body>

        <div class="container">
            <div class="tab tab-1">
                <table id="table" border="1">
                    <tr>        
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Age</th>
                        <th>Delete</th>
                    </tr>
                    <tr>

                    </tr>

                </table>
            </div>
            <div class="tab tab-2">
                First Name :<input type="text" name="fname" id="fname">
                Last Name :<input type="text" name="lname" id="lname">
                Age :<input type="number" name="age" id="age">

                <button onclick="addHtmlTableRow();">Add</button>

            </div>
        </div>

        <script>

            var rIndex,
                table = document.getElementById("table");

            // check the empty input
            function checkEmptyInput()
            {
                var isEmpty = false,
                    fname = document.getElementById("fname").value,
                    lname = document.getElementById("lname").value,
                    age = document.getElementById("age").value;

                if(fname === ""){
                    alert("First Name Connot Be Empty");
                    isEmpty = true;
                }
                else if(lname === ""){
                    alert("Last Name Connot Be Empty");
                    isEmpty = true;
                }
                else if(age === ""){
                    alert("Age Connot Be Empty");
                    isEmpty = true;
                }
                return isEmpty;
            }

            // add Row
            function addHtmlTableRow()
            {
                // get the table by id
                // create a new row and cells
                // get value from input text
                // set the values into row cell's
                if(!checkEmptyInput()){
                var newRow = table.insertRow(table.length),
                    cell1 = newRow.insertCell(0),
                    cell2 = newRow.insertCell(1),
                    cell3 = newRow.insertCell(2),
                    cell4 = newRow.insertCell(3),
                    fname = document.getElementById("fname").value,
                    lname = document.getElementById("lname").value,
                    age = document.getElementById("age").value,
                    edit = "Edit"

                cell1.innerHTML = fname;
                cell2.innerHTML = lname;
                cell3.innerHTML = age;
                cell4.innerHTML = edit;
                // call the function to set the event to the new row
                selectedRowToInput();
            }
            }

            // display selected row data into input text
            function selectedRowToInput()
            {

                for(var i = 1; i < table.rows.length; i++)
                {
                    table.rows[i].onclick = function() 
                    {
                      // get the seected row index
                      rIndex = this.rowIndex;
                      document.getElementById("fname").value = this.cells[0].innerHTML;
                      document.getElementById("lname").value = this.cells[1].innerHTML;
                      document.getElementById("age").value = this.cells[2].innerHTML;
                    };
                }
            }
            selectedRowToInput();


            var index, table = document.getElementById('table');
            for(var i = 1; i < table.rows.length; i++)
            {
                table.rows[i].cells[3].onclick = function() //Line with the error
                {
                    var c = confirm("do you want to delete this row");
                    if(c === true)
                    {
                        index = this.parentElement.rowIndex;
                        table.deleteRow(index);
                    }

                    //console.log(index);
                };

            }



        </script>

    </body>
</html>

任何想法可能是什么问题?,非常感谢

【问题讨论】:

    标签: javascript html script


    【解决方案1】:

    您不需要在函数addHtmlTableRow() 内循环,只需将类添加到Edit,然后使用动态添加的元素设置事件处理程序

    document.addEventListener('click',function(e){
    if(e.target){
          //do something
       }
    });
    

    var rIndex,
      table = document.getElementById("table");
    
    // check the empty input
    function checkEmptyInput() {
      var isEmpty = false,
        fname = document.getElementById("fname").value,
        lname = document.getElementById("lname").value,
        age = document.getElementById("age").value;
    
      if (fname === "") {
        alert("First Name Connot Be Empty");
        isEmpty = true;
      } else if (lname === "") {
        alert("Last Name Connot Be Empty");
        isEmpty = true;
      } else if (age === "") {
        alert("Age Connot Be Empty");
        isEmpty = true;
      }
      return isEmpty;
    }
    
    // add Row
    function addHtmlTableRow() {
      // get the table by id
      // create a new row and cells
      // get value from input text
      // set the values into row cell's
      if (!checkEmptyInput()) {
        var newRow = table.insertRow(table.length),
          cell1 = newRow.insertCell(0),
          cell2 = newRow.insertCell(1),
          cell3 = newRow.insertCell(2),
          cell4 = newRow.insertCell(3),
          fname = document.getElementById("fname").value,
          lname = document.getElementById("lname").value,
          age = document.getElementById("age").value,
          edit = 'Edit';
    
        cell1.innerHTML = fname;
        cell2.innerHTML = lname;
        cell3.innerHTML = age;
        cell4.innerHTML = edit;
        cell4.className = "delete"; // <== add this class
        // call the function to set the event to the new row
        selectedRowToInput();
      }
    }
    
    // display selected row data into input text
    function selectedRowToInput() {
    
      for (var i = 1; i < table.rows.length; i++) {
        table.rows[i].onclick = function() {
          // get the seected row index
          rIndex = this.rowIndex;
          document.getElementById("fname").value = this.cells[0].innerHTML;
          document.getElementById("lname").value = this.cells[1].innerHTML;
          document.getElementById("age").value = this.cells[2].innerHTML;
        };
      }
    }
    selectedRowToInput();
    
    // for deleting row
    document.addEventListener('click', function(e) {
      if (e.target && e.target.classList.contains('delete')) {
        if (confirm("do you want to delete this row")) {
          e.target.parentElement.remove();
        }
      }
    });
    td:last-child {
      background-color: #F00;
      color: #FFF;
      cursor: pointer;
      font-weight: bold;
      text-decoration: underline;
    }
     <div class="container">
       <div class="tab tab-1">
         <table id="table" border="1">
           <tr>
             <th>First Name</th>
             <th>Last Name</th>
             <th>Age</th>
             <th>Delete</th>
           </tr>
           
           <tr>
    
           </tr>
    
         </table>
       </div>
       <div class="tab tab-2">
         First Name :<input type="text" name="fname" id="fname">
         Last Name :<input type="text" name="lname" id="lname">
         Age :<input type="number" name="age" id="age">
    
         <button onclick="addHtmlTableRow();">Add</button>
    
       </div>
     </div>

    【讨论】:

      【解决方案2】:

      基本上在循环的第一次迭代中尝试访问不存在的第三个&lt;td&gt;(单元格)。

      <table id="table" border="1">
                          <tr>        
                              <th>First Name</th>
                              <th>Last Name</th>
                              <th>Age</th>
                              <th>Delete</th>
                          </tr>
               
                          <tr>
                             <!-- there is no cell --> 
                          </tr>
                          
                      </table>
      

      因此出现未定义错误。

      你可以删除它,因为它没有用。

      您应该在向表中插入一些数据后执行循环。 只需将循环包装在一个条件中。 (如果你删除了&lt;tr&gt;,那么我们的条件应该是table.rows.length > 1

          if(table.rows.length > 2){
                 for(var i = 1; i < table.rows.length; i++)
                          {
                              table.rows[i].cells[3].onclick = function() 
                              {
                                  var c = confirm("do you want to delete this row");
                                  if(c === true)
                                  {
                                      index = this.parentElement.rowIndex;
                                      table.deleteRow(index);
                                  }
                                  
                                  //console.log(index);
                              };
                              
                          }
      }
          
      

      【讨论】:

        【解决方案3】:

        Javascript 中的数组从 0 开始。在您的示例中,这意味着:

        - rows[0] = Header row
        - rows[1] = First data row
        - rows[2] = Second data row
        

        等等。您的 for 循环开始计数 1。

        因此,您的for 循环尝试访问表格中的第二 行,但是当页面首次加载时,该行不包含任何单元格。

        这就是脚本说undefined is not an object 的原因。 for 循环将尝试访问row[1].cells[3]row[1] 没有任何单元格。因此,您正在尝试访问一个不存在的单元格。

        【讨论】:

          猜你喜欢
          • 2017-09-12
          • 1970-01-01
          • 2020-12-03
          • 1970-01-01
          • 2021-12-14
          • 2022-07-18
          • 2019-10-31
          • 1970-01-01
          • 2021-01-06
          相关资源
          最近更新 更多