为什么要点两下才能删除一个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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值