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>
  • 相关阅读:
    转 IDEA 解决代码提示功能消失
    模态框居中显示
    DetachedCriteria和Criteria的使用方法
    struts2配置文件详解
    springMVC上传图片
    在linux下运行mongodb
    webSocket客服在线交谈
    接口自动化
    easyui input文本框清除值
    Spring总结
  • 原文地址:https://www.cnblogs.com/heyang78/p/7464909.html
Copyright © 2011-2022 走看看