代码之家  ›  专栏  ›  技术社区  ›  Maksim Vi.

在旧IE浏览器中追加子项

  •  2
  • Maksim Vi.  · 技术社区  · 15 年前

    我正在尝试在我的javascript代码中创建一个新元素,并将其附加到我的一个元素中。但是,旧的IE浏览器似乎不支持这个函数,我的代码在使用AppendChild函数的行中断。

    var child = document.createElement('span');
    child.innerHTML = "Hello World!"; // Crashes here
    parent.appendChild(child); // And here
    

    我能用什么替代IE吗?

    谢谢您。

    这段代码在现代浏览器中运行良好。

    更新: 下面的代码解决了我问题的最后一部分,我可以将空的子级附加到父级:

    var child = document.createElement('span');
    if (parent.insertAdjacentElement){
       parent.insertAdjacentElement('beforeEnd', child);
    }
    else if (parent.appendChild) {
       parent.appendChild(child);
    }
    

    但我仍然需要在子元素中放入一些数据。 createTextNode , innerHTML , setAttributes 不要工作。

    4 回复  |  直到 15 年前
        1
  •  2
  •   ekhaled    15 年前

    这可能与此无关,但请检查 this link 因为别人是如何解决这个问题的

    编辑: this link

        2
  •  0
  •   Jani Hartikainen    15 年前

    在我看来,它在第二条线上崩溃了。innerhtml是用小写i而不是大写来写的。它甚至可能是你的第一行,因为有一个打字错误,但我想这只是个问题。

        3
  •  -1
  •   Eli Grey    15 年前

    这能解决问题吗?

    var child = document.createElement('span');
    child.appendChild(document.createTextNode("Hello World!"));
    parent.appendChild(child);
    
        4
  •  -1
  •   Maksim Vi.    15 年前

    parent.innerHTML 似乎工作得很好。