繁体   English   中英

“未定义不是对象”尝试引用 HTML 中的单元格时

[英]“Undefined is not an object” When trying to reference a cell in HTML

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

“未定义不是 object(评估 '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>

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

基本上在循环的第一次迭代中,尝试访问不存在的第三个<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>

因此出现未定义的错误。

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

您应该在向表中插入一些数据后执行循环。 只需将循环包装在一个条件中。 (如果您删除<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);
                        };
                        
                    }
}
    

您不需要在 function 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>

Javascript 中的 Arrays 从 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]没有任何单元格。 因此,您正在尝试访问一个不存在的单元格。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM