insertAdjacentHTML方法详解

添加HTML内容与文本内容以前用的是innerHTML与innerText方法,最近发现还有insertAdjacentHTML和 insertAdjacentText方法,这两个方法更灵活,可以在指定的地方插入html内容和文本内容。

insertAdjacentText方法与 insertAdjacentHTML方法类似,只不过只能插入纯文本,参数相同

方法名称:insertHtml(where,el,html)

参数介绍:
where:插入位置。包括beforeBegin,beforeEnd,afterBegin,afterEnd。
el:用于参照插入位置的html元素对象
html:要插入的html代码


insertAdjacentHTML 方法:在指定的地方插入html标签语句

原型:insertAdajcentHTML(swhere,stext)

 

参数:

swhere: 指定插入html标签语句的地方,

stext:要插入的内容

 

有四种值可用:

1.     beforeBegin: 插入到标签开始前

2.     afterBegin:插入到标签开始标记之后

3.     beforeEnd:插入到标签结束标记前

4.     afterEnd:插入到标签结束标记后

<html>
     <head>
     <mce:script language="javascript"><!--
     function myfun(){
         var obj = document.getElementById("btn1");
         obj.insertAdjacentHTML("afterEnd","<br><input name="txt1">");
     }
     
// --></mce:script>
     </head>
     <body>
         <input name="txt">
         <input id="btn1" name="btn1" type="button" value="更多" onclick="myfun()">
     </body>
 </html>

 

<html>
 <head>
 <title>24.htm insertAdjacentHTML插入新内容</title>
 <mce:script language="jscript"><!--
 function addsome()
 {
     document.all.paral.insertAdjacentHTML("afterBegin","<h1> 在文本前容器内插入内容1</h1>");
     document.all.paral.insertAdjacentHTML("beforeEnd","<h2> 在文本后容器内插入内容2</h2>");
     document.all.paral.insertAdjacentHTML("beforeBegin","<h4> 在文本前容器外插入内容4</h1>");
     document.all.paral.insertAdjacentHTML("afterEnd","<h5> 在文本后容器外插入内容5</h2>");
 }
 
// --></mce:script>
 </head>
 <body onload="addsome()">
 <div id="paral" style="fontsize:6;color='#ff00ff'" mce_style="fontsize:6;color='#ff00ff'">原来的内容</div><hr>
 </body>
 </html> 

 注意:

1. 这两种方法必须在整个文档装载完成之后才能使用,否则将出错。
2. InsertAdjacentText只能插入普通文本,InsertAdjacentHTML插入html格式的文本
3. 用InsertAdjacentHTML插入脚本,必须在script元素中使用defer属性,否则脚本执行将出现运行期错误
4. InsertAdjacentHTML插入html元素后,all以及其他可能的元素集合将自动更新以反应动态变化。如页面后续元素的sourceIndex 属性将改变。
5. 当赋予InsertHTML/outerHTML属性无效的HTML标签,该方法可能出现运行时错。
6.只有文档BODY内显示的内容能被以上属性和方法动态改变,BODY对象的内容能被动态操作,但BODY对象本身无法被替换。
7.以上属性和方式不能操作空标签(没有内容的html标签),如input,img。
8.对于table对象而言,只有td(innerHTML/innerText)和table(outerHMTL/outerText)对象可以用某些属性来替换或插入内容;而其他table对象,如tr、tbody不能用这些属性来改变内容。

posted @ 2013-03-11 13:19  穆乙  阅读(6044)  评论(2编辑  收藏  举报