zoukankan      html  css  js  c++  java
  • Uncaught TypeError: Cannot read property 'length' of undefined

    <table border="1" width="50%" id="table">
            <tr>
              <th>学号</th>
              <th>姓名</th>
              <th>操作</th>
            </tr>
            <tr>
              <td>xh001</td>
              <td>阮雌</td>
              <td><a href="javascript:;" onclick="delete(this)">删除</a></td>   <!--在删除按钮上添加点击事件  -->
            </tr>
            <tr>
               <td>xh002</td>
               <td>刘赫</td>
               <td><a href="javascript:;" onclick="delete(this)" >删除</a></td>   <!--在删除按钮上添加点击事件  -->
            </tr>
        </table>
        <input type="button" value="添加一行" onclick="add()" />   <!--在添加按钮上添加点击事件  -->
    <script>
            window.onload = function(){
              var tr=document.getElementsByTagName("tr");
              var td=document.getElementsByTagName("td");
             for(var i=0;i<tr.length;i++){
                  var n=1;
                    n++;
                 var k=0;
                 while(k<cells.length){
                     k++;
                 }
                 let cells=tr[i+n].cells;
    //            tr[i+n].cells.innerHTML+="xh00";
                console.log(tr[i+n].cells.length)
             }
         }
    
    报错:没找到length元素,判断下cells是否为underfined或者为空,如是则不遍历,就不会js报错了。
    正确改为:
    window.onload = function(){
    
             var tr=document.getElementsByTagName("tr");
              var td=document.getElementsByTagName("td");
             for(var i=0;i<tr.length;i++){
                  var n=1;
                    n++;
                 var k=0;
                 while(k<tr[i+n].cells.length){
                     k++;
                 }
                 let cells=tr[i+n].cells;
    //            tr[i+n].cells.innerHTML+="xh00";
                console.log(tr[i+n].cells.length)
             }
         }
    </script>
    报错: Uncaught TypeError: Cannot read property 'cells' of undefined,cells元素未定义,书写顺序错误,写在while之前,之后又报了个cell is not defined;
    正确改为:
    <script>
    window.onload = function(){

          var tr=document.getElementsByTagName("tr");
          var td=document.getElementsByTagName("td");
            for(var i=0;i<tr.length;i++){
              var n=1;
                n++;
              let cells=tr[i+n].children;
                for(var j=0; j<cells.length; j++){
                  console.log(cells[j])
                }
                var k=0;
                while(k<tr[i+n].cells.length){
                  k++;
                }
              }
            }

    </script>
  • 相关阅读:
    angular-指令
    microbit 范例课程
    microsoft 为microbit.org 设计的课程
    Microbit 翻译计划及IDE 中文化
    Microbit MicroPython 介绍
    micro:bit 软件生态系统介绍
    Microbit 硬件架构介绍
    TCP协议和UDP协议下的socket
    爬虫-链家二手房
    函数相关
  • 原文地址:https://www.cnblogs.com/aivnfjgj/p/12504747.html
Copyright © 2011-2022 走看看