HTML DOM insertAdjacentHTML() 方法將文本字符串作為 HTML 插入到指定位置。
用法
以下是語法 -
使用 positionString 和 HTML 代碼的參數調用 insertAdjacentHTML()
node.insertAdjacentHTML(“positionString”, “htmlString”)
位置字符串
這裏,“位置字符串”可以是以下 -
位置字符串 | 描述 |
---|---|
afterbegin | 它在節點元素的開頭後插入 htmlString |
afterend | 它在節點元素之後插入 htmlString |
beforebegin | 它在節點元素之前插入 htmlString |
beforeend | 它在節點元素的結尾之前插入 htmlString |
HTML 字符串
並且,“htmlString” 可以是以下內容 -
positionString | <span>new span</span> 或 <p>這是一個新段落</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’按鈕 -
相關用法
- HTML DOM insertAdjacentElement()用法及代碼示例
- HTML DOM insertAdjacentText()用法及代碼示例
- HTML DOM insertBefore()用法及代碼示例
- HTML DOM ins cite屬性用法及代碼示例
- HTML DOM ins dateTime屬性用法及代碼示例
- HTML DOM indexedDB deleteDatabase()用法及代碼示例
- HTML DOM indexedDB databases()用法及代碼示例
- HTML DOM indexedDB cmp()用法及代碼示例
- HTML DOM indexedDB open()用法及代碼示例
- HTML DOM iFrame用法及代碼示例
- HTML DOM item()用法及代碼示例
- HTML DOM isSameNode()用法及代碼示例
- HTML DOM isDefaultNamespace()用法及代碼示例
- HTML DOM isEqualNode()用法及代碼示例
- HTML DOM Style overflowY屬性用法及代碼示例
- HTML DOM Document hidden屬性用法及代碼示例
- HTML DOM IFrame用法及代碼示例
- HTML DOM Textarea cols屬性用法及代碼示例
- HTML DOM Style pageBreakAfter屬性用法及代碼示例
- HTML DOM Base href屬性用法及代碼示例
注:本文由純淨天空篩選整理自AmitDiwan大神的英文原創作品 HTML DOM insertAdjacentHTML() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。