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';
    }
    

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

  • 相关阅读:
    78. Subsets
    93. Restore IP Addresses
    71. Simplify Path
    82. Remove Duplicates from Sorted List II
    95. Unique Binary Search Trees II
    96. Unique Binary Search Trees
    312. Burst Balloons
    程序员社交平台
    APP Store开发指南
    iOS框架搭建(MVC,自定义TabBar)--微博搭建为例
  • 原文地址:https://www.cnblogs.com/jessie-xian/p/11596871.html
Copyright © 2011-2022 走看看