码迷,mamicode.com
首页 > 其他好文 > 详细

为什么要点两下才能删除一个li节点 原来是空白节点作怪

时间:2017-09-01 21:17:19      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:ack   remove   http   html 4.01   class   nbsp   onclick   first   back   

奇怪吧,下面的代码居然要点两次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>

 

为什么要点两下才能删除一个li节点 原来是空白节点作怪

标签:ack   remove   http   html 4.01   class   nbsp   onclick   first   back   

原文地址:http://www.cnblogs.com/xiandedanteng/p/7464909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!