[英]Adding HTML to the end of a container: What is the proper way to do it using JavaScript?
I'm a bit of a web dev n00b, so I do things like this: 我有点像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>";
However, I'm guessing there's a purer way of accomplishing the task of modifying inner HTML. 但是,我猜测有一种更纯粹的方法来完成修改内部HTML的任务。 What is the standard way of doing this? 这样做的标准方法是什么? I assume this sort of procedure is what happens when I post something on an internet forum. 我假设当我在互联网论坛上发布内容时会发生这种程序。 So, it's kind of an important thing to know. 所以,知道它是一件很重要的事情。
I recommend using appendChild
over innerHTML
我建议在innerHTML
使用appendChild
myDiv = document.getElementById("myid");
myNewNode = document.createElement("div")
myContent = document.createTextNode("text of new div");
myNewNode.appendChild(myContent);
myDiv.appendChild(myNewNode);
innerHTML
will remove listeners that are on your existing nodes within the element. innerHTML
将删除元素中现有节点上的侦听器。 appendChild
preserves them. appendChild
保留它们。
If you want to create and append nodes via HTML markup, do so by using .insertAdjacentHTML()
. 如果要通过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>");
Otherwise, use DOM creation/manipulation methods. 否则,使用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.