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