insertAdjacentHTML是IE瀏覽器提供向DOM中插入html字符串的方法,字符串會自動生成在DOM樹中。
其調用方式為elem.insertAdjacentHTML( position, htmlStr )
elem 向哪個DOM的標簽出插入字符串
position 有四個選項 "beforeBegin" "afterEnd" "afterBegin" "beforeEnd"分別指在elem的開始標簽之前、結束標簽之后、開始標簽之后、結束標簽之前插入htmlStr
htmlStr 字符串(不是DOM元素)
以下是在《javascript權威指南》中摘抄的,重新封裝並重命名了該功能的Insert對象。並同時解決insertAdjacentHTML的瀏覽器兼容性問題
/**
* 在開始或結束標簽的前后插入html字符串
* before 在開始標簽之前插入html字符串
* after 在結束標簽之后插入html字符串
* atStart 在開始標簽之后插入字符串
* atEnd 在結束標簽之前插入字符串
*/
Insert = ( function(){
if( document.createElement( "div" ).insertAdjacentHTML ){
return {
// e element, h html
before : function( e, h ){
// beforebegin大小寫均可, h {string} html字符串或text均可
e.insertAdjacentHTML( "beforebegin", h );
},
after : function( e, h ){
e.insertAdjacentHTML( "afterend", h );
},
atStart : function( e, h ){
e.insertAdjacentHTML( "afterbegin", h );
},
atEnd : function( e, h ){
e.insertAdjacentHTML( "beforeEnd", h );
}
};
}
function fragment( html ){
var tmpDiv = document.createElement( "div" ),
frag = document.createDocumentFragment();
tmpDiv.innerHTML = html;
while( tmpDiv.firstChild ){
frag.appendChild( tmpDiv.firstChild );
}
return frag;
}
var Insert = {
before : function( e, h ){
e.parentNode.insertBefore( fragment( h ), e );
},
after : function( e, h ){
// 當e.nextSibling為空時,insertBefore方法會將frament(h)插入到最后
e.parentNode.insertBefore( fragment( h ), e.nextSibling );
},
atStart : function( e, h ){
e.insertBefore( fragment( h ), e.firstChild );
},
atEnd : function(){
e.appendChild( fragment( h ) );
}
};
// 同時解決insertAdjacentHTML的兼容性問題
Element.prototype.insertAdjacentHTML = function( pos, html ){
switch( pos.toLowerCase() ){
case "beforebegin" : return Insert.before( this, html );
case "afterend" : return Insert.after( this, html );
case "afterbegin" : return Insert.atStart( this, html );
case "beforeend" : return Insert.atEnd( this, html );
}
};
return Insert;
}() );
