"Undefined is not an object" 尝试引用 HTML 中的单元格时

"Undefined is not an object" When trying to reference a cell in HTML

我正在尝试使用网站上用户的数据制作 table。我添加了擦除该行的选项,但出现错误

"undefined is not an object (evaluating 'table.rows[i].cells[3]')"

如果我使用固定的 table,我的代码可以工作,但是使用脚本制作 table editable 它不起作用,这是我的代码:

<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 中的数组从 0 开始。在您的示例中,这意味着:

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

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

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

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

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

<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>

因此出现未定义错误。

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

你应该在向 table 中插入一些数据后执行循环。 只需将循环包装在一个条件中。 (如果删除 <tr> 那么我们的条件应该是 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);
                        };
                        
                    }
}
    

您不需要在函数内部循环 addHtmlTableRow() 只需将 class 添加到 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>