代码很简单,请看:如果此时直接点击test按钮,IE8报错。Chrome以及Firefox均报错。似乎是代码的问题。
将document.getElementById("test1")修改为document.getElementById("test2")
再点击test按钮,IE8 Chrome Firefox均正确执行。显然问题似乎是dd元素前不允许执行插入dom元素的。请问大家该如何解决该问题?appendChild方法不适合我需要的结构,所以不能使用。谢谢。<head>
  <title>Untitled Page</title>
  <script type="text/javascript">
    
    function test()
    {
      var fra=document.createDocumentFragment();
      var a=document.createElement("dd");
      a.setAttribute("id","http://www.sohu.com");
      a.innerHTML="www.sohu.com";
      fra.appendChild(a);
      document.body.insertBefore(fra,document.getElementById("test1"));
    }
    
  </script>
</head>
<body><dl>
<dt>测试</dt>
<dd id="test1">111111111111111</dd>
</dl><div id="test2">test</div><input type="button" value="test" onclick="test()" />
</body>

解决方案 »

  1.   

    <head>
    <title>Untitled Page</title>
    <script type="text/javascript">
    function test() {
    var fra=document.createDocumentFragment();
    var a=document.createElement("dd");
    a.setAttribute("id","http://www.sohu.com");
    a.innerHTML="www.sohu.com";
    fra.appendChild(a);
    var test1 = document.getElementById("test1");
    test1.parentNode.insertBefore(fra, test1);
    }
    </script>
    </head>
    <body>
    <dl>
    <dt>测试</dt>
    <dd id="test1">111111111111111</dd>
    </dl>
    <div id="test2">test</div>
    <input type="button" value="test" onclick="test()" />
    </body>
      

  2.   

    很明显,test1的容器(parentNode)是<dl>,test2的容器是<body>test1不直接在body容器中,还有一层dl
      

  3.   

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title>无标题页</title>
        <script type="text/javascript">
        function CreateElement()
        {
          var fra=document.createDocumentFragment();
          var hh=document.createElement("dd");
          hh.setAttribute("id","d1");
          hh.innerHTML="http://blog.csdn.net/ws_hgo";
          fra.appendChild(hh);
          
          var ce=document.getElementById("ce");
          ce.parentNode.insertBefore(fra,ce);
        }
        </script>
    </head>
    <body>
    <dl>
    <dd id="ce">测试</dd>
    </dl>
    <div>
        <input id="Button1" type="button" value="ClickMe" onclick="CreateElement();" />
    </div>
    </body>
    </html>
      

  4.   

    楼主的插入位置不对,以后你做的时候可以把innerHTML打印出来,每次打印一下
      

  5.   

    感觉有疑惑,
    要是这个问题的话 用  document.all.test1怎么也不可以啊
    还有 去掉<dl>  和 </dl> 这两个标签之后, 为什么 document.body.insertBefore(fra,document.getElementById("test2"));有不可以用了?显然问题不是出在 多了一个标签嵌套上。