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

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

  • 相关阅读:
    Delphi 实现C语言函数调用
    Delphi采用接口实现DLL调用
    select、poll、epoll之间的区别总结[整理]
    int 的重载
    qt 安装包生成2
    线程池的简单实现
    qt 安装包生成
    linux 下tftpf搭建
    2018C语言助教总结
    动态规划——最长子序列长度
  • 原文地址:https://www.cnblogs.com/jessie-xian/p/11596871.html
Copyright © 2011-2022 走看看