HTML DOM insertAdjacentHTML() 方法
HTML DOM insertAdjacentHTML() 方法將文字字串作為 HTML 插入到指定位置。
語法
以下是語法 −
使用 positionString 和 HTML 程式碼引數呼叫 insertAdjacentHTML()
node.insertAdjacentHTML(“positionString”, “htmlString”)
位置字串
此處“positionString”可以是以下內容 −
| positionString | 說明 |
|---|---|
| afterbegin | 它在節點元素開頭後插入 htmlString |
| afterend | 它在節點元素後插入 htmlString |
| beforebegin | 它在節點元素前插入 htmlString |
| beforeend | 它在節點元素結束前插入 htmlString |
html 字串
並且“htmlString”可以是以下內容 −
| positionString | <span>new span</span> 或 <p>This is a new paragraph</p> 或任何其他有效的 html 程式碼 |
示例
讓我們看一個 InsertAdjacentHTML() 方法的示例 −
<!DOCTYPE html>
<html>
<head>
<title>insertAdjacentHTML()</title>
<style>
form {
width:70%;
margin: 0 auto;
text-align: center;
}
* {
padding: 2px;
margin:5px;
}
input[type="button"] {
border-radius: 10px;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>insertAdjacentHTML( )</legend>
<h1>Family Tree</h1>
<span id="GrandFather">Grand Father --></span>
<span id="Father">Father --></span>
<span id="Myself">Myself</span>
<input type="button" onclick="rectifyTree()" value="Son is born">
</fieldset>
</form>
<script>
function rectifyTree() {
var MSpan = document.getElementById("Myself");
MSpan.insertAdjacentHTML("afterend", "<span id='Son'>-->Son</span>");
}
</script>
</body>
</html>輸出
這將產生以下輸出 −
在單擊“Son is born”(兒子出生)按鈕之前 −

在單擊“Son is born”(兒子出生)按鈕之後 −

廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP