简体   繁体   English

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

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

相关问题 为Javascript函数转义HTML的正确方法是什么? - What is a proper way to escape HTML for Javascript function? 在使用AJAX获取html内容后,将侦听器添加到新元素的正确方法是什么? (jQuery,Javascript) - What is a proper way to add listeners to new elements after using AJAX to get the html content? (jQuery, Javascript) 将HTML从控制器传递到Javascript的正确方法是什么? - What is the proper way of passing HTML from the controller to Javascript? 使用JavaScript检索HTML文本框数据的正确方法 - Proper way to retrive HTML textbox data using JavaScript 使用Javascript的window.opener的正确方法是什么? - What's the proper way of using Javascript's window.opener? <a>用Javascript / JQuery</a>替换` <a>`</a>的正确方法是<a>什么?</a> - What's the proper way to replace `<a>` using Javascript/JQuery? 使用 JavaScript 测试输入是韩文还是中文的正确方法是什么? - What is proper way to test if the input is Korean or Chinese using JavaScript? 使用Jquery来停止css动画。 这样做的正确方法是什么? - Using Jquery to stop css animation. What is the proper way to do this? 使用 Javascript 编写 HTML 的正确方法是什么? - What is the correct way to write HTML using Javascript? 使用 CSS 和 Javascript 向 HTML DOM 对象添加动画的正确方法是什么? - What is the correct way of adding animation to an HTML DOM object with CSS and Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM