添加HTML内容与文本内容以前用的是innerHTML与innerText方法,
最近发现还有insertAdjacentHTML和 insertAdjacentText方法,
这两个方法更灵活,可以在指定的地方插入html内容和文本内容。
insertAdjacentText方法与 insertAdjacentHTML方法类似,只不过只能插入纯文本,参数相同
insertAdjacentHTML 方法:在指定的地方插入html标签语句
swhere: 指定插入html标签语句的地方,
stext:要插入的内容
2. afterBegin:插入到标签开始标记之后
3. beforeEnd:插入到标签结束标记前
最近发现还有insertAdjacentHTML和 insertAdjacentText方法,
这两个方法更灵活,可以在指定的地方插入html内容和文本内容。
insertAdjacentText方法与 insertAdjacentHTML方法类似,只不过只能插入纯文本,参数相同
insertAdjacentHTML 方法:在指定的地方插入html标签语句
原型:insertAdajcentHTML(swhere,stext)
参数:swhere: 指定插入html标签语句的地方,
stext:要插入的内容
有四种值可用:
1. beforeBegin: 插入到标签开始前2. afterBegin:插入到标签开始标记之后
3. beforeEnd:插入到标签结束标记前
4. afterEnd:插入到标签结束标记后
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>insertAdjacentHTML1</title>
<style type="text/css">
#one{ border:1px solid #ddd;}
</style>
</head>
<body>
<div id="one">insertAdjacentHTML</div>
<script type="text/javascript">
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('beforeBegin', '<div class="a">beforeBegin</div>');
d1.insertAdjacentHTML('afterBegin', '<div class="b">afterBegin</div>');
d1.insertAdjacentHTML('beforeEnd', '<div class="c">beforeEnd</div>');
d1.insertAdjacentHTML('afterend', '<div class="d">afterend</div>');
</script>
</body>
</html>
结果如下: