簡體   English   中英

如何使用 JS 將內容添加到 html 正文?

[英]How to add content to html body using JS?

我的 html <body>有很多<section>並且想通過 javascript 添加更多內容。 但是,使用innerHTML只是用新的部分替換我現有的部分,而不是將它們添加到舊部分中。

我還能用什么?

您可以使用

document.getElementById("parentID").appendChild(/*..your content created using DOM methods..*/)

或者

document.getElementById("parentID").innerHTML+= "new content"

我剛剛遇到了一個類似於這個問題的解決方案,其中包含一些性能統計信息。

下面的示例似乎更快:

 document.getElementById('container').insertAdjacentHTML('beforeend', '<div id="idChild"> content html </div>');

InnerHTML vs jQuery 1 vs appendChild vs innerAdjecentHTML。

在此處輸入圖像描述

參考:1)性能統計2) API - insertAdjacentHTML

我希望這將有所幫助。

我認為如果您想直接將內容添加到正文中,最好的方法是:

document.body.innerHTML += "bla bla";

要替換它,請使用:

document.body.innerHTML = "bla bla";

嘗試以下語法:

document.body.innerHTML += "<p>My new content</p>";

你可能正在使用

document.getElementById('element').innerHTML = "New content"

試試這個:

document.getElementById('element').innerHTML += "New content"

或者,最好使用DOM Manipulation

document.getElementById('element').appendChild(document.createElement("div"))

與使用innerHTML相比,Dom 操作更innerHTML ,因為innerHTML只是將字符串轉儲到文檔中。 瀏覽器將不得不重新解析整個文檔以獲取它的結構。

工作演示:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
onload = function(){
var divg = document.createElement("div");
divg.appendChild(document.createTextNode("New DIV"));
document.body.appendChild(divg);
};
</script>
</head>
<body>

</body>
</html>

在大多數瀏覽器中,您可以使用 javascript 變量而不是document.getElementById 假設您的 html 正文內容是這樣的:

<section id="mySection"> Hello </section>

然后您可以將mySection稱為 javascript 中的變量:

mySection.innerText += ', world'
// same as: document.getElementById('mySection').innerText += ', world'

看到這個片段:

 mySection.innerText += ', world!'
 <section id="mySection"> Hello </section>

只是:

    document.getElementById('myDiv').innerHTMl += "New Content";

最近,我遇到了同樣的問題,但我想在正文內容的開頭添加內容。 所以我發現這個解決方案值得:在指定位置時使用insertAdjecentHTML(positions, text) 該位置可以是'beforebegin''afterbegin''beforeend''afterend'

const element = document.getElementById('my-id')

element.insertAdjacentHTML(position, text);

你也可以這樣做

document.querySelector("#yourid").append('<div>my element<div>');
document.querySelector('body').appendChild( //your content )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM