zoukankan      html  css  js  c++  java
  • JavaScript对列表节点的操作:删除指定节点、删除最后一个节点、删除第一个节点、删除所有节点、增加节点

    使用菜鸟的运行环境直接测试:http://www.runoob.com/try/try.php?filename=tryjs_events

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>菜鸟教程(runoob.com)</title>
    <script>
    function removeFirstNode(){
    
        var node = document.getElementsByTagName("li");
        document.getElementById("list").removeChild(node[0]);
        
    }    
    function removeLastNode(){
    
        var node = document.getElementsByTagName("li");
        document.getElementById("list").removeChild(node[node.length-1]);
        
    }
    function addChild(){
        var node = document.createElement('li');
        node.setAttribute("onclick", "removeElement(this)"); 
        var content = document.getElementById('content').value;
        var textnode = document.createTextNode(content);
        node.appendChild(textnode)
        document.getElementById('list').appendChild(node);
        
    }
    function clearAll(){
        document.getElementById("list").innerHTML='';
    }    
    function removeElement(_element){
     var _parentElement = _element.parentNode;
     if(_parentElement){
      _parentElement.removeChild(_element);
     }
    }
        
    </script>
    </head>
    <body>
    <input id="content" placeholder="节点内容" value="" />
    <button type="button" onclick="removeFirstNode()">删除第一个节点</button>
    <button type="button" onclick="removeLastNode()">删除最后一个节点</button>
    <button type="button" onclick="addChild()">增加节点</button>
    <button type="button" onclick="clearAll()">清除节点</button>    
        
    <ul id="list"> 
    
        <li onclick="removeElement(this)">Pretty row 1  </li> 
    
        <li onclick="removeElement(this)">Pretty row 2  </li> 
    </ul> 
    
    </body>
    </html>
  • 相关阅读:
    洛谷 P1226 【模板】快速幂||取余运算 题解
    洛谷 P2678 跳石头 题解
    洛谷 P2615 神奇的幻方 题解
    洛谷 P1083 借教室 题解
    洛谷 P1076 寻宝 题解
    洛谷 UVA10298 Power Strings 题解
    洛谷 P3375 【模板】KMP字符串匹配 题解
    Kafka Shell基本命令
    Mybatis与Hibernate的详细对比
    MyBatis简介
  • 原文地址:https://www.cnblogs.com/shengulong/p/8980297.html
Copyright © 2011-2022 走看看