zoukankan      html  css  js  c++  java
  • 提示:Cannot set property 'height' of undefined

    <html>
    <head>
    <script>
    window.onload=function(){
    var oUl = document.getElementById("ul1");
    var i=0;
    for(i=0;i<oUl.childNodes.length;i++){
    oUl.childNodes[i].style.height=30+'px';
    }
    }
    </script>
    <style type='text/css'>
    </style>
    </head>
    <body>
    <ul id='ul1'>
    <li>jason</li>
    <li>rekken</li>
    <li>guo</li>
    </ul>
    </body>
    </html>
    

    运行之后报Cannot set property 'height' of undefined错误

    IE下childNodes取得的节点不包括文本节点,而在Chrome或Firefox下得到的节点包括文本节点,具体看下面代码的执行结果:

    var oUl = document.getElementById("ul1");
    console.log(oUl.childNodes); // [text, li, text, li, text, li, text]
    

    在代码中,当循环childNodes的时候,第一个节点是textNode,不具备style属性,所以会报'undefined';

    常见的解决方法有两种:

    // 方法一
    var oUl = document.getElementById("ul1");
    var i=0;
    var children = oUl.childNodes;
    for(i = 0; i < children.length; i++){
        if (children[i].nodeType === 1) {
            children[i].style.background = 'red';
        }
    }
     
    // 方法二
    var oUl = document.getElementById("ul1");
    var i=0;
    var children = oUl.children;
    for(i = 0; i < children.length; i++){
        children[i].style.background = 'red';
    }
    

    两种方法都能达到想要的效果,且解决了报错的问题

  • 相关阅读:
    CentOS 用命令访问网页
    ngalian(一)2:安装npm环境
    数仓建设原则探讨
    C#中获取系统时间 LZU
    判断是否是数字类 LZU
    Extjs中ComboBoxTree的实现 LZU
    SQL之学生选课数据库 LZU
    如何看书 LZU
    面向对象思想 LZU
    C#控件命名规范 LZU
  • 原文地址:https://www.cnblogs.com/jessie-xian/p/11596871.html
Copyright © 2011-2022 走看看