2014-03-30 17 views
3

我有点Web开发的n00b,所以我做这样的事情:将HTML添加到容器的末尾:使用JavaScript执行此操作的正确方法是什么?

document.getElementById("some_element").innerHTML += "<p>Here's some more that will be added to the end of the HTML that composes some_element</p>"; 

不过,我猜有完成修改内部HTML的任务更纯的方式。这样做的标准方式是什么?我假设这种程序是当我在互联网论坛上发布内容时发生的情况。所以,这是一件重要的事情要知道。

回答

5

我建议使用appendChild超过innerHTML

myDiv = document.getElementById("myid"); 
myNewNode = document.createElement("div") 
myContent = document.createTextNode("text of new div"); 
myNewNode.appendChild(myContent); 
myDiv.appendChild(myNewNode); 

innerHTML将删除是元素中的现有节点上的监听器。 appendChild保留它们。

+1

为什么你将HTML传递给'createTextNode()'? –

1

如果要通过HTML标记创建和追加节点,请使用.insertAdjacentHTML()来完成。

elem.insertAdjacentHTML("beforeend", "<p>Here's some more that will be added to the end of the HTML that composes some_element</p>"); 

否则,使用DOM创建/操作方法。

elem.appendChild(document.createElement("p")) 
    .appendChild(document.createTextNode("Here's some more that will be added to the end of the HTML that composes some_element")); 
相关问题