zoukankan      html  css  js  c++  java
  • 为什么要点两下才能删除一个li节点 原来是空白节点作怪

    奇怪吧,下面的代码居然要点两次button才能删除一个li节点:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
     <head>
      <title> New Document </title>
     </head>
    
     <body>
    <ul id="myUl"> <!-- 这样会有空白节点  -->
    <li>111</li>
    <li>222</li>
    <li>333</li>
    </ul>
    
      <button onclick="removeLi();" >removeLi</button>
     </body>
    </html>
    
    <script type="text/javascript">
    <!--
        // 奇怪吗?为什么要点两下
        function removeLi(){
            var ul=document.getElementById("myUl");
            var li=ul.firstChild;
            ul.removeChild(li);        
        }
    //-->
    </script>

    用ul.childNodes.length查看一下,原来是空白节点在作怪,这样就好了:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
     <head>
      <title> New Document </title>
     </head>
    
     <body>
    <ul id="myUl"><li>111</li><li>222</li><li>333</li></ul> <!-- 这样就消除了空白节点,firstChild是第一个li了  -->
    
      <button onclick="removeLi();" >removeLi</button>
     </body>
    </html>
    
    <script type="text/javascript">
    <!--
        // 现在一下就删除li
        function removeLi(){
            var ul=document.getElementById("myUl");
            var li=ul.firstChild;
            ul.removeChild(li);        
        }
    //-->
    </script>

    选ul的子节点时限定li也可行:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
     <head>
      <title> New Document </title>
     </head>
    
     <body>
    <ul id="myUl">
    <li>111</li>
    <li>222</li>
    <li>333</li>
    </ul>
    
      <button onclick="removeLi();" >removeLi</button>
     </body>
    </html>
    
    <script type="text/javascript">
    <!--
        // 
        function removeLi(){
            var ul=document.getElementById("myUl");
            var li=ul.getElementsByTagName("li")[0];// 这样直接无视空白节点,是推荐做法
            ul.removeChild(li);        
        }
    //-->
    </script>
  • 相关阅读:
    ZROI2018提高day5t1
    noi.ac day1t1 candy
    ARC102E Stop. Otherwise...
    TOP命令详解(负载情况)
    mysql 时间函数 时间转换函数
    maven编译时错误:无效的目标发行版
    jsp base路径
    mybatis typehandler
    终极解决方案 at org.apache.jsp.index_jsp._jspInit(index_jsp.java:22) 报空指针
    【转】 IntelliJ IDEA像Eclipse一样打开多个项目
  • 原文地址:https://www.cnblogs.com/heyang78/p/7464909.html
Copyright © 2011-2022 走看看