zoukankan      html  css  js  c++  java
  • [dom] children属性的陷阱

      children是个好属性,通过这个属性取得的节点不饱和文本节点,如果使用childNodes的话会包括文本节点。这个属性首先有ie进入,现在已经跨浏览器。使用他可以减少我们过滤节点的操作。

    兼容情况见http://www.quirksmode.org/dom/w3c_core.html

    <!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
    <title></title>
    </head>
    <body>
    <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <!-- xxx -->
    </ul>
    <script type="text/javascript">
    (function(window,doc,undefined){
    var childs=doc.getElementsByTagName('ul')[0].children;
    console.log(childs.length);
    })(window,document)
    </script>
    </body>
    </html>



    如果使用这段代码的话,大部分浏览器返回的节点数都是6

    这次中枪的是ie8,

    ie8会把注释节点也算做有效节点,这个问题只出现ie8上,所以要使用这个属性要记得过滤文本节点。ppk的站点上也特别说明了这点。

  • 相关阅读:
    标准模板库中的链表(list)
    C++接口
    qsort
    C++异常
    标准模板库中的向量(vector)
    后缀表达式/逆波兰表达式
    静态数据成员
    c++存储区域
    #define 和 const
    Git 的下载与安装
  • 原文地址:https://www.cnblogs.com/enix/p/2417788.html
Copyright © 2011-2022 走看看