zoukankan      html  css  js  c++  java
  • JS-DOM操作应用

    父级.appendChild(子节点)

    父级.insertBefore(子节点,在谁之前)

    <title>无标题文档</title>
    <script>
    window.onload=function ()
    {
        var oBtn=document.getElementById('btn1');
        var oUl=document.getElementById('ull');
        var oTxt=document.getElementById('txt1');
        
        oBtn.onclick=function ()
        {
            var oLi=document.createElement('li');
            var aLi=oUl.getElementsByTagName('li');
            oLi.innerHTML=oTxt.value;
            
            if(aLi.length>0)
            {
                oUl.insertBefore(oLi,aLi[0]);
            }else
            {
                oUl.appendChild(oLi);
                }
        }
    }
    </script>
    </head>
    
    <body>
    <input id="txt1" type="text"/>
    <input id="btn1" type="button" value="创建li"/>
    <ul id="ull">
    </ul>
    </body>

    父级.removeChild(子节点)

    <title>无标题文档</title>
    <script>
    window.onload=function ()
    {
        var aA=document.getElementsByTagName('a');
        var oUl=document.getElementById('ull');
        
        for(var i=0;i<aA.length;i++)
        {
            aA[i].onclick=function ()
            {
                oUl.removeChild(this.parentNode);
            }
        }
    }
    </script>
    </head>
    
    <body>
    <ul id="ull">
        <li>23451253<a href="javascript:;">删除</a></li>
        <li>fwefw<a href="javascript:;">删除</a></li>
        <li>sdgvsdaf<a href="javascript:;">删除</a></li>
        <li>bvdfde<a href="javascript:;">删除</a></li>
        <li>45646<a href="javascript:;">删除</a></li>
    </ul>
    </body>

    文档碎片

    文档碎片可以提高DOM操作性能(理论上)   /*现在IE9,火狐浏览器性能都有所提高,影响不大*/

    document.createDocumentFragment()

    <title>无标题文档</title>
    <script>
    window.onload=function ()
    {
        var oUl=document.getElementById('ull');
        var oFrag=document.createDocumentFragment();
        
        for(var i=0;i<10000;i++)
        {
            var oLi=document.createElement('li');
            oFrag.appendChild(oLi);
        }
        oUl.appendChild(oFrag);
    }
    </script>
    </head>
    
    <body>
    <ul id="ull"></ul>
    </body>
  • 相关阅读:
    Html5页面返回机制解决方案
    Linux(Fedora)下NodeJs升级最新版本(制定版本)
    fedora23开发环境搭建手册
    fedora安装sublime text教程
    实现斐波那契数列之es5、es6
    选择城市下拉框中选择框右对齐,文本右对齐问题
    前端笔记(二)
    前端基础笔记(一)
    解决点击输入框弹出软键盘导致弹窗失效的问题
    angularJS之ng-bind与ng-bind-template的区别
  • 原文地址:https://www.cnblogs.com/919czzl/p/4314593.html
Copyright © 2011-2022 走看看