添加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不能用這些屬性來改變內容。
