[英]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.