繁体   English   中英

将HTML添加到容器的末尾:使用JavaScript执行此操作的正确方法是什么?

[英]Adding HTML to the end of a container: What is the proper way to do it using JavaScript?

我有点像web dev n00b,所以我这样做:

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的任务。 这样做的标准方法是什么? 我假设当我在互联网论坛上发布内容时会发生这种程序。 所以,知道它是一件很重要的事情。

我建议在innerHTML使用appendChild

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

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

如果要通过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"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM