javascript之DOM技术(一)

http://tech.ddvip.com   2008年01月18日    社区交流

本文详细介绍javascript之DOM技术(一)

  下面介绍常用的几个方法

  (2)createElement(),createTextNode(),appendChild()

  例子:

<html>
  <head>
    <title>createElement() Example</title>
    <script type="text/javascript">
      function createMessage() {
        var oP = document.createElement("p");
        var oText = document.createTextNode("Hello World!");
        oP.appendChild(oText);
        document.body.appendChild(oP);
      }
    </script>
  </head>
  <body onload="createMessage()">
  </body>
</html>

  在页面载入后,创建节点oP,并创建一个文本节点oText,oText通过appendChild方法附加在oP节点上,为了实际显示出来,将oP节点通过appendChild方法附加在body节点上。此例子将显示Hello World!

  (3)removeChild(),replaceChild()和insertBefore()

  从方法名称就知道是干什么的:删除节点,替换节点,插入节点。需要注意的是replaceChild和insertBefore两个参数都是新节点在前,旧节点在后。

  (4)createDocumentFragment()

  此方法主要是为了解决大量添加节点时,速度过慢。通过创建一个文档碎片节点,将要添加的新节点附加在此碎片节点上,然后再将文档碎片节点append到body上面,替代多次append到body节点。

  例子:

<html>
  <head>
    <title>insertBefore() Example</title>
    <script type="text/javascript">
      function addMessages() {
        var arrText = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth"];
        
        var oFragment = document.createDocumentFragment();
        
        for (var i=0; i < arrText.length; i++) {
          var oP = document.createElement("p");
          var oText = document.createTextNode(arrText[i]);
          oP.appendChild(oText);
          oFragment.appendChild(oP);
        }
        
        document.body.appendChild(oFragment);
  
      }
    </script>
  </head>
  <body onload="addMessages()">
  
  </body>
</html>

作者:killme2008    责编:豆豆技术应用

正在加载评论...