JavaScript高级程序设计 学习笔记之DOM基础(三)

5、在原有元素之前添加元素显示消息,insertBefore()

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <title>JSP Page</title>

        <script type="text/javascript">

            function insertMessage(){

                var oNewP=document.createElement("p");//创建新元素

                var oNewText=document.createTextNode("Hello Universite");//创建文本

                oNewP.appendChild(oNewText);//为节点添加文本

                var oOldP=document.getElementsByTagName("p")[0];

                //   document.body.insertBefore(oNewP,oOldP);//将新元素消息插入老元素消息之后

                //也可替换为

                oOldP.parentNode.insertBefore(oNewP,oOldP);

            }

        </script>

    </head>

    <body  onload="insertMessage()">

        <p>hello world</p>

    </body>

</html>

显示效果:

Hello Universite

hello world

6、创建文档碎片,为了提升性能。createDocumentFragment

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <title>JSP Page</title>

        <script type="text/javascript">

            function createFragment(){

               //创建文本碎片为了便于提升性能,当调用文档碎片时,只刷新一次页面

               //而在以前的传统做法是调用十次document.body.appendChild()

                //节点文本数组

                var arrText=["first","second","third","fourth","fifth","sixth","seventh","eighth","nineth","tenth"];

                var oFragment=document.createDocumentFragment();//创建文档碎片

                for(var i=0;i<arrText.length;i++){

                    var oP=document.createElement("p");//创建元素p

                    var oText=document.createTextNode(arrText[i]);//创建文本为将每个文本数组的循环内容

                    oP.appendChild(oText);//文本添加到元素中

                    oFragment.appendChild(oP);//将每个元素文本添加到文档碎片中

                }

                document.body.appendChild(oFragment);//添加文档碎片到body

           

            }

        </script>

    </head>

    <body  onload="createFragment()">

    </body>

</html>

显示效果如下:

First

Second

Third

Fourth

Fifth

Sixth

Seventh

Eighth

Nineth

tenth

你可能感兴趣的:(JavaScript,html,jsp)